Skip to content

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

fix: prevent copy-ignored from copying nested worktrees (#645)

Maximilian Roosd97c0e99dcad
diff --git a/.claude-plugin/skills/worktrunk/reference/step.md b/.claude-plugin/skills/worktrunk/reference/step.md
index 5fd0cd942..dc1b0e12f 100644
--- a/.claude-plugin/skills/worktrunk/reference/step.md
+++ b/.claude-plugin/skills/worktrunk/reference/step.md
@@ -266,7 +266,7 @@ Only gitignored files are copied — tracked files are never touched. If `.workt
- Uses copy-on-write (reflink) when available for space-efficient copies
- Handles nested `.gitignore` files, global excludes, and `.git/info/exclude`
- Skips existing files (safe to re-run)
-- Skips symlinks and `.git` entries
+- Skips `.git` entries and other worktrees
### Performance
diff --git a/docs/content/step.md b/docs/content/step.md
index 477342d9f..a50d8d535 100644
--- a/docs/content/step.md
+++ b/docs/content/step.md
@@ -285,7 +285,7 @@ Only gitignored files are copied — tracked files are never touched. If `.workt
- Uses copy-on-write (reflink) when available for space-efficient copies
- Handles nested `.gitignore` files, global excludes, and `.git/info/exclude`
- Skips existing files (safe to re-run)
-- Skips symlinks and `.git` entries
+- Skips `.git` entries and other worktrees
### Performance
diff --git a/src/cli/step.rs b/src/cli/step.rs
index c2320289b..8fae01644 100644
--- a/src/cli/step.rs
+++ b/src/cli/step.rs
@@ -198,7 +198,7 @@ Only gitignored files are copied — tracked files are never touched. If `.workt
- Uses copy-on-write (reflink) when available for space-efficient copies
- Handles nested `.gitignore` files, global excludes, and `.git/info/exclude`
- Skips existing files (safe to re-run)
-- Skips symlinks and `.git` entries
+- Skips `.git` entries and other worktrees
## Performance
diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rs
index fc7ccb347..5cd9780cc 100644
--- a/src/commands/step_commands.rs
+++ b/src/commands/step_commands.rs
@@ -7,7 +7,7 @@
//! - `handle_rebase` - Rebase onto target branch
//! - `step_copy_ignored` - Copy gitignored files matching .worktreeinclude
-use std::path::Path;
+use std::path::{Path, PathBuf};
use anyhow::Context;
use color_print::cformat;
@@ -498,6 +498,23 @@ pub fn step_copy_ignored(
ignored_entries
};
+ // Filter out entries that contain other worktrees (prevents recursive copying when
+ // worktrees are nested inside the source, e.g., worktree-path = ".worktrees/...")
+ let worktree_paths: Vec<PathBuf> = repo
+ .list_worktrees()?
+ .into_iter()
+ .map(|wt| wt.path)
+ .collect();
+ let entries_to_copy: Vec<_> = entries_to_copy
+ .into_iter()
+ .filter(|(entry_path, _)| {
+ // Exclude if any worktree (other than source) is inside or equal to this entry
+ !worktree_paths
+ .iter()
+ .any(|wt_path| wt_path != &source_path && wt_path.starts_with(entry_path))
+ })
+ .collect();
+
if entries_to_copy.is_empty() {
crate::output::print(info_message("No matching files to copy"))?;
return Ok(());
@@ -647,16 +664,27 @@ fn copy_dir_recursive_fallback(src: &Path, dest: &Path) -> anyhow::Result<()> {
for entry in fs::read_dir(src)? {
let entry = entry?;
let file_type = entry.file_type()?;
-
- // Skip symlinks
- if file_type.is_symlink() {
- continue;
- }
-
let src_path = entry.path();
let dest_path = dest.join(entry.file_name());
- if file_type.is_dir() {
+ if file_type.is_symlink() {
+ // Copy symlink (preserves the link, doesn't follow it)
+ if !dest_path.exists() {
+ let target = fs::read_link(&src_path)?;
+ #[cfg(unix)]
+ std::os::unix::fs::symlink(&target, &dest_path)?;
+ #[cfg(windows)]
+ {
+ // Check source to determine symlink type (target may be relative/broken)
+ let is_dir = src_path.metadata().map(|m| m.is_dir()).unwrap_or(false);
+ if is_dir {
+ std::os::windows::fs::symlink_dir(&target, &dest_path)?;
+ } else {
+ std::os::windows::fs::symlink_file(&target, &dest_path)?;
+ }
+ }
+ }
+ } else if file_type.is_dir() {
copy_dir_recursive_fallback(&src_path, &dest_path)?;
} else {
// Skip existing files for idempotent hook usage
diff --git a/tests/integration_tests/step_copy_ignored.rs b/tests/integration_tests/step_copy_ignored.rs
index d851cdd88..897add192 100644
--- a/tests/integration_tests/step_copy_ignored.rs
+++ b/tests/integration_tests/step_copy_ignored.rs
@@ -600,3 +600,58 @@ fn test_copy_ignored_bare_repo() {
".env should be copied to feature worktree"
);
}
+
+/// Test that worktrees nested inside the source are not copied (GitHub issue #641)
+///
+/// When worktree-path is configured to place worktrees inside the primary worktree
+/// (e.g., `.worktrees/{{ branch | sanitize }}`), copy-ignored should NOT copy
+/// those nested worktrees, as this would cause recursive copying.
+#[rstest]
+fn test_copy_ignored_skips_nested_worktrees(mut repo: TestRepo) {
+ // Create a .worktrees directory inside the main repo (simulating worktree-path = ".worktrees/...")
+ let nested_worktrees_dir = repo.root_path().join(".worktrees");
+ fs::create_dir_all(&nested_worktrees_dir).unwrap();
+
+ // Create a worktree inside .worktrees/ using raw git commands
+ let nested_worktree_path = nested_worktrees_dir.join("feature-nested");
+ repo.git_command()
+ .args([
+ "worktree",
+ "add",
+ "-b",
+ "feature-nested",
+ nested_worktree_path.to_str().unwrap(),
+ ])
+ .output()
+ .unwrap();
+
+ // Add .worktrees to .gitignore (typical for this setup)
+ fs::write(repo.root_path().join(".gitignore"), ".worktrees/\n").unwrap();
+
+ // Also create a regular ignored file that SHOULD be copied
+ fs::write(repo.root_path().join(".env"), "SECRET=value").unwrap();
+ fs::write(repo.root_path().join(".gitignore"), ".worktrees/\n.env\n").unwrap();
+
+ // Create another worktree (outside the main repo, using default path)
+ let dest_path = repo.add_worktree("destination");
+
+ // Run copy-ignored
+ assert_cmd_snapshot!(make_snapshot_cmd(
+ &repo,
+ "step",
+ &["copy-ignored"],
+ Some(&dest_path),
+ ));
+
+ // Verify: .env was copied (regular ignored file)
+ assert!(
+ dest_path.join(".env").exists(),
+ ".env should be copied to destination"
+ );
+
+ // Verify: .worktrees was NOT copied (contains a worktree)
+ assert!(
+ !dest_path.join(".worktrees").exists(),
+ ".worktrees directory should NOT be copied (contains nested worktree)"
+ );
+}
diff --git a/tests/snapshots/integration__integration_tests__step_copy_ignored__copy_ignored_skips_nested_worktrees.snap b/tests/snapshots/integration__integration_tests__step_copy_ignored__copy_ignored_skips_nested_worktrees.snap
new file mode 100644
index 000000000..291bd2cd6
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__step_copy_ignored__copy_ignored_skips_nested_worktrees.snap
@@ -0,0 +1,35 @@
+---
+source: tests/integration_tests/step_copy_ignored.rs
+info:
+ program: wt
+ args:
+ - step
+ - copy-ignored
+ 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
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ 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 -----
+
+----- stderr -----
+✓ Copied 1 entry