Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix: 3 bugs found via adversarial testing (#944)
Maximilian Roose124dbf65de3
diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rsindex 34f835fca..beed7c222 100644--- a/src/commands/worktree/switch.rs+++ b/src/commands/worktree/switch.rs@@ -345,21 +345,22 @@ fn resolve_switch_target(.resolve_worktree_name(branch).context("Failed to resolve branch name")?;- // Resolve and validate base+ // Resolve and validate base (only when --create is set)let resolved_base = if let Some(base_str) = base {- let resolved = repo.resolve_worktree_name(base_str)?;if !create {eprintln!("{}",warning_message("--base flag is only used with --create, ignoring"));None- } else if !repo.ref_exists(&resolved)? {- return Err(GitError::ReferenceNotFound {- reference: resolved,- }- .into());} else {+ let resolved = repo.resolve_worktree_name(base_str)?;+ if !repo.ref_exists(&resolved)? {+ return Err(GitError::ReferenceNotFound {+ reference: resolved,+ }+ .into());+ }Some(resolved)}} else {@@ -647,8 +648,6 @@ pub fn execute_switch(expected_path,new_previous,} => {- let _ = repo.set_switch_previous(new_previous.as_deref());-let current_dir = std::env::current_dir().ok().and_then(|p| canonicalize(&p).ok());@@ -657,6 +656,13 @@ pub fn execute_switch(.map(|cur| cur == &path).unwrap_or(false);+ // Only update switch history when actually switching worktrees.+ // Updating on AlreadyAt would corrupt `wt switch -` by recording+ // the current branch as "previous" even though no switch occurred.+ if !already_at_worktree {+ let _ = repo.set_switch_previous(new_previous.as_deref());+ }+let mismatch_path = if !paths_match(&path, &expected_path) {Some(expected_path)} else {diff --git a/src/config/expansion.rs b/src/config/expansion.rsindex a509c6e6a..477bc2359 100644--- a/src/config/expansion.rs+++ b/src/config/expansion.rs@@ -232,15 +232,13 @@ pub fn expand_template(repo: &Repository,name: &str,) -> Result<String, String> {- // Build context map, optionally shell-escaping values+ // Build context map with raw values (shell escaping is applied at output time via formatter)let mut context = HashMap::new();for (key, value) in vars {- let val = if shell_escape {- escape(Cow::Borrowed(*value)).to_string()- } else {- (*value).to_string()- };- context.insert(key.to_string(), minijinja::Value::from(val));+ context.insert(+ key.to_string(),+ minijinja::Value::from((*value).to_string()),+ );}// Render template with minijinja@@ -251,6 +249,20 @@ pub fn expand_template(if shell_escape {// Preserve trailing newlines in templates (important for multiline shell commands)env.set_keep_trailing_newline(true);++ // Shell-escape values at output time, not before template rendering.+ // This ensures filters (sanitize, sanitize_db, etc.) operate on raw values+ // and the escaping is applied to the final output, preventing corruption+ // when filters modify already-escaped strings.+ env.set_formatter(|out, _state, value| {+ if value.is_none() {+ return Ok(());+ }+ let s = value.to_string();+ let escaped = escape(Cow::Borrowed(&s));+ write!(out, "{escaped}")?;+ Ok(())+ });}// Register custom filters@@ -262,22 +274,16 @@ pub fn expand_template(});env.add_filter("hash_port", |value: String| string_to_port(&value));- // Register worktree_path_of_branch function for looking up branch worktree paths- // The function returns shell-escaped paths when shell_escape is true, matching- // how regular template variables are handled.+ // 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.let repo_clone = repo.clone();env.add_function("worktree_path_of_branch", move |branch: String| -> String {- let path = repo_clone+ repo_clone.worktree_for_branch(&branch).ok().flatten().map(|p| to_posix_path(&p.to_string_lossy()))- .unwrap_or_default();- if shell_escape && !path.is_empty() {- escape(Cow::Borrowed(&path)).to_string()- } else {- path- }+ .unwrap_or_default()});// Cache verbosity level for consistent behavior within this call@@ -719,6 +725,32 @@ mod tests {expand_template("{{ branch }}", &vars, false, &test.repo, "test").unwrap(),"feature/foo");++ // Shell escaping + sanitize: filters operate on raw values, escaping applied at output.+ // Previously, shell escaping was applied BEFORE filters, corrupting the result+ // when values contained shell-special characters (quotes, backslashes).+ vars.insert("branch", "user's/feature");+ let result =+ expand_template("{{ branch | sanitize }}", &vars, true, &test.repo, "test").unwrap();+ // sanitize replaces / with -, producing "user's-feature"+ // shell_escape wraps it: 'user'\''s-feature' (valid shell for user's-feature)+ assert_eq!(result, "'user'\\''s-feature'", "sanitize + shell escape");++ // Without the fix, pre-escaping would produce corrupted output because+ // sanitize would replace the / and \ in the already-escaped value.++ // Shell escaping without filter: raw value with special chars+ let result = expand_template("{{ branch }}", &vars, true, &test.repo, "test").unwrap();+ // shell_escape wraps: 'user'\''s/feature' (valid shell for user's/feature)+ assert_eq!(+ result, "'user'\\''s/feature'",+ "shell escape without filter"+ );++ // Shell-escape formatter handles none values (renders as empty string)+ let result =+ expand_template("prefix-{{ none }}-suffix", &vars, true, &test.repo, "test").unwrap();+ assert_eq!(result, "prefix--suffix", "none renders as empty");}#[test]diff --git a/src/config/test.rs b/src/config/test.rsindex 206f16b26..1af648184 100644--- a/src/config/test.rs+++ b/src/config/test.rs@@ -251,8 +251,9 @@ fn test_expand_template_nested_curly_braces() {).unwrap();- // Renders as {main}- assert_eq!(result, "echo {main}");+ // Renders as '{main}' — curly braces are shell metacharacters (brace expansion)+ // so the formatter correctly escapes the concatenated result+ assert_eq!(result, "echo '{main}'");}// Snapshot tests for shell escaping behaviordiff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rsindex 10cadc4b6..a08054421 100644--- a/tests/integration_tests/switch.rs+++ b/tests/integration_tests/switch.rs@@ -2929,3 +2929,63 @@ fn test_switch_mr_glab_not_installed(#[from(repo_with_remote)] repo: TestRepo) {assert_cmd_snapshot!("switch_mr_glab_not_installed", cmd);});}++/// Bug fix: switching to the current worktree (AlreadyAt) must NOT update switch history.+///+/// Previously, `wt switch foo` while already in `foo` would record `foo` as the+/// previous branch, corrupting `wt switch -` so it pointed to the current branch+/// instead of the actual previous one.+#[rstest]+fn test_switch_already_at_preserves_history(repo: TestRepo) {+ // Create a feature branch with worktree+ repo.run_git(&["branch", "hist-feature"]);++ // Step 1: Switch from main to hist-feature (establishes history: previous=main)+ let feature_path = repo.root_path().parent().unwrap().join(format!(+ "{}.hist-feature",+ repo.root_path().file_name().unwrap().to_str().unwrap()+ ));+ snapshot_switch_from_dir(+ "already_at_preserves_history_1_to_feature",+ &repo,+ &["hist-feature"],+ repo.root_path(),+ );++ // Step 2: Switch to hist-feature again while already there (AlreadyAt)+ // This should NOT update history+ snapshot_switch_from_dir(+ "already_at_preserves_history_2_noop",+ &repo,+ &["hist-feature"],+ &feature_path,+ );++ // Step 3: `wt switch -` should still go to main (the real previous),+ // not to hist-feature (which the bug would have recorded)+ snapshot_switch_from_dir(+ "already_at_preserves_history_3_dash_to_main",+ &repo,+ &["-"],+ &feature_path,+ );+}++/// Bug fix: `--base` without `--create` should warn, not error.+///+/// Previously, `--base -` was resolved (calling resolve_worktree_name) before+/// checking the `--create` flag. When there was no previous branch in history,+/// this produced "No previous branch found" instead of the expected+/// "--base flag is only used with --create, ignoring" warning.+#[rstest]+fn test_switch_base_without_create_warns_not_errors(repo: TestRepo) {+ repo.run_git(&["branch", "base-test"]);++ // No switch history exists, so resolving `-` would fail.+ // But --base without --create should just warn and ignore the flag.+ snapshot_switch(+ "switch_base_without_create_warns",+ &repo,+ &["base-test", "--base", "-"],+ );+}diff --git a/tests/snapshots/integration__integration_tests__switch__already_at_preserves_history_1_to_feature.snap b/tests/snapshots/integration__integration_tests__switch__already_at_preserves_history_1_to_feature.snapnew file mode 100644index 000000000..f0c94a52c--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__already_at_preserves_history_1_to_feature.snap@@ -0,0 +1,43 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - switch+ - hist-feature+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"+ PATH: "[PATH]"+ PSModulePath: ""+ RUST_LOG: warn+ SHELL: ""+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ WT_TEST_DELAYED_STREAM_MS: "-1"+ WT_TEST_EPOCH: "1735776000"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----++----- stderr -----+[32m✓[39m [32mCreated worktree for [1mhist-feature[22m @ [1m_REPO_.hist-feature[22m[39m+[33m▲[39m [33mCannot change directory — shell integration not installed[39m+[2m↳[22m [2mTo enable automatic cd, run [90mwt config shell install[39m[22mdiff --git a/tests/snapshots/integration__integration_tests__switch__already_at_preserves_history_2_noop.snap b/tests/snapshots/integration__integration_tests__switch__already_at_preserves_history_2_noop.snapnew file mode 100644index 000000000..6447b00d8--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__already_at_preserves_history_2_noop.snap@@ -0,0 +1,42 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - switch+ - hist-feature+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"+ PATH: "[PATH]"+ PSModulePath: ""+ RUST_LOG: warn+ SHELL: ""+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ WT_TEST_DELAYED_STREAM_MS: "-1"+ WT_TEST_EPOCH: "1735776000"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----++----- stderr -----+[2m○[22m Already on worktree for [1mhist-feature[22m @ [1m_REPO_.hist-feature[22m+[2m↳[22m [2mTo enable automatic cd, run [90mwt config shell install[39m[22mdiff --git a/tests/snapshots/integration__integration_tests__switch__already_at_preserves_history_3_dash_to_main.snap b/tests/snapshots/integration__integration_tests__switch__already_at_preserves_history_3_dash_to_main.snapnew file mode 100644index 000000000..4f548a46c--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__already_at_preserves_history_3_dash_to_main.snap@@ -0,0 +1,42 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - switch+ - "-"+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"+ PATH: "[PATH]"+ PSModulePath: ""+ RUST_LOG: warn+ SHELL: ""+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ WT_TEST_DELAYED_STREAM_MS: "-1"+ WT_TEST_EPOCH: "1735776000"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----++----- stderr -----+[33m▲[39m [33mWorktree for [1mmain[22m @ [1m_REPO_[22m, but cannot change directory — shell integration not installed[39m+[2m↳[22m [2mTo enable automatic cd, run [90mwt config shell install[39m[22mdiff --git a/tests/snapshots/integration__integration_tests__switch__switch_base_without_create_warns.snap b/tests/snapshots/integration__integration_tests__switch__switch_base_without_create_warns.snapnew file mode 100644index 000000000..33c620004--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__switch_base_without_create_warns.snap@@ -0,0 +1,46 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - switch+ - base-test+ - "--base"+ - "-"+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"+ PATH: "[PATH]"+ PSModulePath: ""+ RUST_LOG: warn+ SHELL: ""+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ WT_TEST_DELAYED_STREAM_MS: "-1"+ WT_TEST_EPOCH: "1735776000"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----++----- stderr -----+[33m▲[39m [33m--base flag is only used with --create, ignoring[39m+[32m✓[39m [32mCreated worktree for [1mbase-test[22m @ [1m_REPO_.base-test[22m[39m+[33m▲[39m [33mCannot change directory — shell integration not installed[39m+[2m↳[22m [2mTo enable automatic cd, run [90mwt config shell install[39m[22m