Skip to content

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

fix(list): correct current worktree detection for nested worktrees (#697)

Maximilian Roos2936bfaa70ef
diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rs
index fb05d842a..c26e325dd 100644
--- a/src/commands/list/collect/mod.rs
+++ b/src/commands/list/collect/mod.rs
@@ -292,15 +292,14 @@ pub fn collect(
Vec::new()
};
- // Detect current worktree by checking if repo path is inside any worktree.
- // This avoids a git command - we just compare canonicalized paths.
- let repo_path_canonical = canonicalize(repo.discovery_path()).ok();
- let current_worktree_path = repo_path_canonical.as_ref().and_then(|repo_path| {
- worktrees.iter().find_map(|wt| {
- canonicalize(&wt.path)
- .ok()
- .filter(|wt_path| repo_path.starts_with(wt_path))
- })
+ // 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.
+ let current_worktree_path = repo.current_worktree().root().ok().and_then(|root| {
+ worktrees
+ .iter()
+ .find(|wt| wt.path == root)
+ .map(|wt| wt.path.clone())
});
// Show warning if user configured a default branch that doesn't exist locally
if let Some(configured) = repo.invalid_default_branch_config() {
diff --git a/tests/common/mod.rs b/tests/common/mod.rs
index 1a11f40b3..4ca8861f5 100644
--- a/tests/common/mod.rs
+++ b/tests/common/mod.rs
@@ -1460,6 +1460,21 @@ impl TestRepo {
canonical_path
}
+ /// Creates a worktree at a custom path (for testing nested worktrees).
+ ///
+ /// Unlike `add_worktree`, this places the worktree at the specified path
+ /// rather than using the default sibling layout.
+ pub fn add_worktree_at_path(&mut self, branch: &str, path: &Path) -> PathBuf {
+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();
+ let path_str = path.to_str().unwrap();
+ self.run_git(&["worktree", "add", "-b", branch, path_str]);
+
+ let canonical_path = canonicalize(path).unwrap();
+ self.worktrees
+ .insert(branch.to_string(), canonical_path.clone());
+ canonical_path
+ }
+
/// Creates a worktree for the main branch (required for merge operations)
///
/// This is a convenience method that creates a worktree for the main branch
diff --git a/tests/integration_tests/list.rs b/tests/integration_tests/list.rs
index 0ad18e73d..16b1b4854 100644
--- a/tests/integration_tests/list.rs
+++ b/tests/integration_tests/list.rs
@@ -2487,3 +2487,55 @@ fn test_list_full_with_nonexistent_default_branch(repo: TestRepo) {
cmd
});
}
+
+/// Tests that the current worktree indicator (@) is correct for nested worktrees.
+///
+/// When worktrees are placed inside other worktrees (e.g., `.worktrees/` layout),
+/// the current detection must use git rev-parse --show-toplevel to correctly identify
+/// which worktree contains the cwd, rather than prefix matching which would match
+/// the parent worktree first.
+///
+/// Regression test for: prefix matching with starts_with would incorrectly match
+/// the main worktree when running from a nested worktree.
+#[rstest]
+fn test_list_nested_worktree_current_indicator(mut repo: TestRepo) {
+ // Create a worktree nested inside the main repo (like .worktrees/ layout)
+ let nested_path = repo.root_path().join(".worktrees").join("feature");
+ let nested_worktree = repo.add_worktree_at_path("feature", &nested_path);
+
+ // Run wt list from inside the nested worktree
+ // The @ indicator should appear on "feature", not on "main"
+ assert_cmd_snapshot!(list_snapshots::command(&repo, &nested_worktree));
+}
+
+/// Tests JSON output for nested worktrees shows is_current on the correct worktree.
+#[rstest]
+fn test_list_nested_worktree_json_is_current(mut repo: TestRepo) {
+ // Create a worktree nested inside the main repo
+ let nested_path = repo.root_path().join(".worktrees").join("feature");
+ let nested_worktree = repo.add_worktree_at_path("feature", &nested_path);
+
+ // Run wt list --format=json from inside the nested worktree
+ let output = repo
+ .wt_command()
+ .current_dir(&nested_worktree)
+ .args(["list", "--format=json"])
+ .output()
+ .unwrap();
+
+ let json: Vec<serde_json::Value> = serde_json::from_slice(&output.stdout).unwrap();
+
+ // Find the worktree entries
+ let main_wt = json.iter().find(|w| w["branch"] == "main").unwrap();
+ let feature_wt = json.iter().find(|w| w["branch"] == "feature").unwrap();
+
+ // feature should be current, main should not
+ assert_eq!(
+ feature_wt["is_current"], true,
+ "Nested worktree 'feature' should be marked as current"
+ );
+ assert_eq!(
+ main_wt["is_current"], false,
+ "Parent worktree 'main' should NOT be marked as current"
+ );
+}
diff --git a/tests/snapshots/integration__integration_tests__list__list_nested_worktree_current_indicator.snap b/tests/snapshots/integration__integration_tests__list__list_nested_worktree_current_indicator.snap
new file mode 100644
index 000000000..4744c5ae4
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__list__list_nested_worktree_current_indicator.snap
@@ -0,0 +1,43 @@
+---
+source: tests/integration_tests/list.rs
+info:
+ program: wt
+ args:
+ - list
+ 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]"
+ RUST_LOG: warn
+ SHELL: ""
+ SOURCE_DATE_EPOCH: "1735776000"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+ Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
+@ feature ⚑_ ./.worktrees/feature 05a4a45d 16h Initial commit
+^ main ? ^| . | 05a4a45d 16h Initial commit
++ feature-a ↑ ↑1 ../repo.feature-a 1b87d473 16h Add feature-a file
++ feature-b ↑ ↑1 ../repo.feature-b f62940fc 16h Add feature-b file
++ feature-c ↑ ↑1 ../repo.feature-c 345c7c93 16h Add feature-c file
+
+○ Showing 5 worktrees, 1 with changes, 3 ahead
+
+----- stderr -----