Skip to content

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

fix: address 5 bugs in template expansion, caching, and concurrency (#847)

Maximilian Roosa2335ba3f5d3
diff --git a/src/commands/list/ci_status/cache.rs b/src/commands/list/ci_status/cache.rs
index d560c055c..dda059c5e 100644
--- a/src/commands/list/ci_status/cache.rs
+++ b/src/commands/list/ci_status/cache.rs
@@ -19,6 +19,9 @@ use super::PrStatus;
/// Uses file-based caching instead of git config to avoid file locking issues.
/// On Windows, concurrent `git config` writes can temporarily lock `.git/config`,
/// causing other git operations to fail with "Permission denied".
+///
+/// Note: Old cache entries without the `branch` field will fail deserialization
+/// and be treated as cache misses — they will be re-fetched with the new format.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct CachedCiStatus {
/// The cached CI status (None means no CI found for this branch)
@@ -27,6 +30,8 @@ pub(crate) struct CachedCiStatus {
pub checked_at: u64,
/// The HEAD commit SHA when the status was fetched
pub head: String,
+ /// The original branch name (for display in `wt config state show`)
+ pub branch: String,
}
impl CachedCiStatus {
@@ -107,6 +112,11 @@ impl CachedCiStatus {
return;
}
+ // On Windows, fs::rename may fail if target exists (depending on Windows version
+ // and filesystem). Remove target first to ensure rename succeeds.
+ #[cfg(windows)]
+ let _ = fs::remove_file(&path);
+
if let Err(e) = fs::rename(&temp_path, &path) {
log::debug!("Failed to rename CI cache file for {}: {}", branch, e);
// Clean up temp file on failure
@@ -133,10 +143,9 @@ impl CachedCiStatus {
return None;
}
- let branch = path.file_stem()?.to_str()?.to_string();
let json = fs::read_to_string(&path).ok()?;
let cached: Self = serde_json::from_str(&json).ok()?;
- Some((branch, cached))
+ Some((cached.branch.clone(), cached))
})
.collect()
}
diff --git a/src/commands/list/ci_status/mod.rs b/src/commands/list/ci_status/mod.rs
index 1d5258fce..6b04f36e7 100644
--- a/src/commands/list/ci_status/mod.rs
+++ b/src/commands/list/ci_status/mod.rs
@@ -379,6 +379,7 @@ impl PrStatus {
status: status.clone(),
checked_at: now_secs,
head: local_head.to_string(),
+ branch: branch.full_name.clone(),
};
cached.write(repo, &branch.full_name);
diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rs
index 4dfde3dea..c7e019e17 100644
--- a/src/commands/list/collect/mod.rs
+++ b/src/commands/list/collect/mod.rs
@@ -299,10 +299,11 @@ pub fn collect(
// Detect current worktree using git rev-parse --show-toplevel (via WorkingTree::root).
// This correctly handles worktrees placed inside other worktrees (e.g., .worktrees/ layout)
// by letting git resolve the actual worktree root rather than using prefix matching.
+ // Canonicalize both paths to handle symlinks (e.g., macOS /var -> /private/var).
let current_worktree_path = repo.current_worktree().root().ok().and_then(|root| {
worktrees
.iter()
- .find(|wt| wt.path == root)
+ .find(|wt| canonicalize(&wt.path).map(|p| p == root).unwrap_or(false))
.map(|wt| wt.path.clone())
});
// Show warning if user configured a default branch that doesn't exist locally
diff --git a/src/config/expansion.rs b/src/config/expansion.rs
index 61cbc8471..bad89cca5 100644
--- a/src/config/expansion.rs
+++ b/src/config/expansion.rs
@@ -263,14 +263,21 @@ 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.
let repo_clone = repo.clone();
env.add_function("worktree_path_of_branch", move |branch: String| -> String {
- repo_clone
+ let path = repo_clone
.worktree_for_branch(&branch)
.ok()
.flatten()
.map(|p| to_posix_path(&p.to_string_lossy()))
- .unwrap_or_default()
+ .unwrap_or_default();
+ if shell_escape && !path.is_empty() {
+ escape(Cow::Borrowed(&path)).to_string()
+ } else {
+ path
+ }
});
// Cache verbosity level for consistent behavior within this call
diff --git a/src/shell_exec.rs b/src/shell_exec.rs
index 4f7e1b017..31510efab 100644
--- a/src/shell_exec.rs
+++ b/src/shell_exec.rs
@@ -39,6 +39,8 @@ fn max_concurrent_commands() -> usize {
std::env::var("WORKTRUNK_MAX_CONCURRENT_COMMANDS")
.ok()
.and_then(|s| s.parse().ok())
+ // 0 = no limit (use usize::MAX as effectively unlimited)
+ .map(|n: usize| if n == 0 { usize::MAX } else { n })
.unwrap_or(DEFAULT_CONCURRENT_COMMANDS)
}
@@ -890,6 +892,17 @@ fn forward_signal_with_escalation(pgid: i32, sig: i32) {
mod tests {
use super::*;
+ #[test]
+ fn test_max_concurrent_commands_defaults() {
+ // When no env var is set, default should be used
+ assert!(max_concurrent_commands() >= 1, "Default should be >= 1");
+ assert_eq!(
+ max_concurrent_commands(),
+ DEFAULT_CONCURRENT_COMMANDS,
+ "Without env var, should use default"
+ );
+ }
+
#[test]
fn test_shell_config_is_available() {
let config = ShellConfig::get();
diff --git a/tests/integration_tests/config_state.rs b/tests/integration_tests/config_state.rs
index 600ee3815..5a4a168e6 100644
--- a/tests/integration_tests/config_state.rs
+++ b/tests/integration_tests/config_state.rs
@@ -609,7 +609,7 @@ fn test_state_clear_all_comprehensive(repo: TestRepo) {
write_ci_cache(
&repo,
"feature",
- r#"{"checked_at":1704067200,"head":"abc123"}"#,
+ r#"{"checked_at":1704067200,"head":"abc123","branch":"feature"}"#,
);
// Logs
@@ -699,7 +699,7 @@ fn test_state_get_with_ci_entries(repo: TestRepo) {
&repo,
"feature",
&format!(
- r#"{{"status":{{"ci_status":"passed","source":"pull-request","is_stale":false}},"checked_at":{TEST_EPOCH},"head":"abc12345def67890"}}"#
+ r#"{{"status":{{"ci_status":"passed","source":"pull-request","is_stale":false}},"checked_at":{TEST_EPOCH},"head":"abc12345def67890","branch":"feature"}}"#
),
);
@@ -707,14 +707,16 @@ fn test_state_get_with_ci_entries(repo: TestRepo) {
&repo,
"bugfix",
&format!(
- r#"{{"status":{{"ci_status":"failed","source":"branch","is_stale":true}},"checked_at":{TEST_EPOCH},"head":"111222333444555"}}"#
+ r#"{{"status":{{"ci_status":"failed","source":"branch","is_stale":true}},"checked_at":{TEST_EPOCH},"head":"111222333444555","branch":"bugfix"}}"#
),
);
write_ci_cache(
&repo,
"main",
- &format!(r#"{{"status":null,"checked_at":{TEST_EPOCH},"head":"deadbeef12345678"}}"#),
+ &format!(
+ r#"{{"status":null,"checked_at":{TEST_EPOCH},"head":"deadbeef12345678","branch":"main"}}"#
+ ),
);
let output = wt_state_get_cmd(&repo).output().unwrap();
@@ -755,7 +757,7 @@ fn test_state_get_comprehensive(repo: TestRepo) {
&repo,
"feature",
&format!(
- r#"{{"status":{{"ci_status":"passed","source":"pull-request","is_stale":false}},"checked_at":{TEST_EPOCH},"head":"abc12345def67890"}}"#
+ r#"{{"status":{{"ci_status":"passed","source":"pull-request","is_stale":false}},"checked_at":{TEST_EPOCH},"head":"abc12345def67890","branch":"feature"}}"#
),
);
@@ -812,7 +814,7 @@ fn test_state_get_json_comprehensive(repo: TestRepo) {
&repo,
"feature",
&format!(
- r#"{{"status":{{"ci_status":"passed","source":"pull-request","is_stale":false}},"checked_at":{TEST_EPOCH},"head":"abc12345def67890"}}"#
+ r#"{{"status":{{"ci_status":"passed","source":"pull-request","is_stale":false}},"checked_at":{TEST_EPOCH},"head":"abc12345def67890","branch":"feature"}}"#
),
);
@@ -885,14 +887,14 @@ fn test_state_clear_ci_status_all_with_entries(repo: TestRepo) {
&repo,
"feature",
&format!(
- r#"{{"status":{{"ci_status":"passed","source":"pull-request","is_stale":false}},"checked_at":{TEST_EPOCH},"head":"abc12345"}}"#
+ r#"{{"status":{{"ci_status":"passed","source":"pull-request","is_stale":false}},"checked_at":{TEST_EPOCH},"head":"abc12345","branch":"feature"}}"#
),
);
write_ci_cache(
&repo,
"bugfix",
&format!(
- r#"{{"status":{{"ci_status":"failed","source":"branch","is_stale":false}},"checked_at":{TEST_EPOCH},"head":"def67890"}}"#
+ r#"{{"status":{{"ci_status":"failed","source":"branch","is_stale":false}},"checked_at":{TEST_EPOCH},"head":"def67890","branch":"bugfix"}}"#
),
);
@@ -910,7 +912,7 @@ fn test_state_clear_ci_status_all_single_entry(repo: TestRepo) {
&repo,
"feature",
&format!(
- r#"{{"status":{{"ci_status":"passed","source":"pull-request","is_stale":false}},"checked_at":{TEST_EPOCH},"head":"abc12345"}}"#
+ r#"{{"status":{{"ci_status":"passed","source":"pull-request","is_stale":false}},"checked_at":{TEST_EPOCH},"head":"abc12345","branch":"feature"}}"#
),
);
diff --git a/tests/integration_tests/doc_templates.rs b/tests/integration_tests/doc_templates.rs
index a3f4397cc..aa6d0da09 100644
--- a/tests/integration_tests/doc_templates.rs
+++ b/tests/integration_tests/doc_templates.rs
@@ -509,3 +509,69 @@ fn test_worktree_path_of_branch_function_registered(repo: TestRepo) {
);
assert_eq!(result.unwrap(), "");
}
+
+/// Test that worktree_path_of_branch returns shell-escaped paths when shell_escape=true.
+///
+/// This is a regression test for the bug where worktree_path_of_branch returned raw paths
+/// even when shell_escape=true, which could break hook commands on paths with spaces
+/// like "/Users/john/My Projects/feature".
+#[rstest]
+fn test_worktree_path_of_branch_shell_escape(repo: TestRepo) {
+ // Create a worktree with a space in the path to test shell escaping
+ let worktree_path = repo.root_path().parent().unwrap().join("My Worktree");
+
+ // Create a new branch and worktree
+ repo.run_git(&["branch", "test-branch"]);
+ repo.run_git(&[
+ "worktree",
+ "add",
+ worktree_path.to_str().unwrap(),
+ "test-branch",
+ ]);
+
+ let repository = Repository::at(repo.root_path()).unwrap();
+ let vars: HashMap<&str, &str> = HashMap::new();
+
+ // With shell_escape=false, path is returned literally
+ let result_literal = expand_template(
+ "{{ worktree_path_of_branch('test-branch') }}",
+ &vars,
+ false,
+ &repository,
+ "test",
+ )
+ .unwrap();
+ // Path should contain "My Worktree" unescaped (spaces as-is, posix-style)
+ assert!(
+ result_literal.contains("My Worktree"),
+ "Expected literal path with space, got: {result_literal}"
+ );
+
+ // With shell_escape=true, path should be escaped for safe shell usage
+ let result_escaped = expand_template(
+ "{{ worktree_path_of_branch('test-branch') }}",
+ &vars,
+ true,
+ &repository,
+ "test",
+ )
+ .unwrap();
+ // Path should be quoted or escaped (shell_escape crate uses single quotes)
+ assert!(
+ result_escaped.contains('\'') || result_escaped.contains('\\'),
+ "Expected shell-escaped path, got: {result_escaped}"
+ );
+ // The escaped path should still reference the worktree
+ assert!(
+ result_escaped.contains("My Worktree") || result_escaped.contains("My\\ Worktree"),
+ "Escaped path should reference worktree: {result_escaped}"
+ );
+
+ // Clean up worktree
+ repo.run_git(&[
+ "worktree",
+ "remove",
+ "--force",
+ worktree_path.to_str().unwrap(),
+ ]);
+}
diff --git a/tests/integration_tests/list.rs b/tests/integration_tests/list.rs
index b78c95592..2f8cad6e3 100644
--- a/tests/integration_tests/list.rs
+++ b/tests/integration_tests/list.rs
@@ -1586,7 +1586,7 @@ fn mock_ci_status(repo: &TestRepo, branch: &str, status: &str, source: &str, is_
// Build the cache JSON (matches CachedCiStatus struct)
let cache_json = format!(
- r#"{{"status":{{"ci_status":"{}","source":"{}","is_stale":{}}},"checked_at":{},"head":"{}"}}"#,
+ r#"{{"status":{{"ci_status":"{}","source":"{}","is_stale":{}}},"checked_at":{},"head":"{}","branch":"{}"}}"#,
status,
source,
is_stale,
@@ -1594,7 +1594,8 @@ fn mock_ci_status(repo: &TestRepo, branch: &str, status: &str, source: &str, is_
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs(),
- head
+ head,
+ branch
);
// Get git common dir for cache location