Skip to content

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

fix: improve `copy-ignored` verbose output, error context, and symlink handling (#1090)

Maximilian Roosb1fb430f849c
diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rs
index 2bb2c11c9..943930e7d 100644
--- a/src/commands/step_commands.rs
+++ b/src/commands/step_commands.rs
@@ -20,6 +20,7 @@ use worktrunk::config::UserConfig;
use worktrunk::git::Repository;
use worktrunk::styling::{
eprintln, format_with_gutter, hint_message, info_message, progress_message, success_message,
+ verbosity,
};
use super::command_approval::approve_hooks;
@@ -642,10 +643,11 @@ pub fn step_copy_ignored(
return Ok(());
}
+ let verbose = verbosity();
let mut copied_count = 0;
- // Handle dry-run: show what would be copied in a gutter list
- if dry_run {
+ // Show entries in verbose or dry-run mode
+ if verbose >= 1 || dry_run {
let items: Vec<String> = entries_to_copy
.iter()
.map(|(src_entry, is_dir)| {
@@ -657,16 +659,19 @@ pub fn step_copy_ignored(
})
.collect();
let entry_word = if items.len() == 1 { "entry" } else { "entries" };
+ let verb = if dry_run { "Would copy" } else { "Copying" };
eprintln!(
"{}",
info_message(format!(
- "Would copy {} {}:\n{}",
+ "{verb} {} {}:\n{}",
items.len(),
entry_word,
format_with_gutter(&items.join("\n"), None)
))
);
- return Ok(());
+ if dry_run {
+ return Ok(());
+ }
}
// Copy entries
@@ -678,11 +683,13 @@ pub fn step_copy_ignored(
let dest_entry = dest_path.join(relative);
if *is_dir {
- copy_dir_recursive(src_entry, &dest_entry, force)?;
+ copy_dir_recursive(src_entry, &dest_entry, force)
+ .with_context(|| format!("copying directory {}", relative.display()))?;
copied_count += 1;
} else {
if let Some(parent) = dest_entry.parent() {
- fs::create_dir_all(parent)?;
+ fs::create_dir_all(parent)
+ .with_context(|| format!("creating directory for {}", relative.display()))?;
}
if force {
remove_if_exists(&dest_entry)?;
@@ -691,7 +698,11 @@ pub fn step_copy_ignored(
match reflink_copy::reflink_or_copy(src_entry, &dest_entry) {
Ok(_) => copied_count += 1,
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
- Err(e) => return Err(e.into()),
+ Err(e) => {
+ return Err(
+ anyhow::Error::from(e).context(format!("copying {}", relative.display()))
+ );
+ }
}
}
}
@@ -787,7 +798,7 @@ fn copy_dir_recursive(src: &Path, dest: &Path, force: bool) -> anyhow::Result<()
///
/// Used as fallback when atomic directory clone isn't available or fails.
fn copy_dir_recursive_fallback(src: &Path, dest: &Path, force: bool) -> anyhow::Result<()> {
- fs::create_dir_all(dest)?;
+ fs::create_dir_all(dest).with_context(|| format!("creating directory {}", dest.display()))?;
for entry in fs::read_dir(src)? {
let entry = entry?;
@@ -800,23 +811,18 @@ fn copy_dir_recursive_fallback(src: &Path, dest: &Path, force: bool) -> anyhow::
if force {
remove_if_exists(&dest_path)?;
}
- 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)?;
- }
- }
+ // Use symlink_metadata to detect broken symlinks (exists() follows symlinks
+ // and returns false for broken ones, causing EEXIST on the next symlink call)
+ if dest_path.symlink_metadata().is_err() {
+ let target = fs::read_link(&src_path)
+ .with_context(|| format!("reading symlink {}", src_path.display()))?;
+ create_symlink(&target, &src_path, &dest_path)?;
}
} else if file_type.is_dir() {
copy_dir_recursive_fallback(&src_path, &dest_path, force)?;
+ } else if !file_type.is_file() {
+ // Skip non-regular files (sockets, FIFOs, etc.)
+ log::debug!("skipping non-regular file: {}", src_path.display());
} else {
if force {
remove_if_exists(&dest_path)?;
@@ -825,7 +831,11 @@ fn copy_dir_recursive_fallback(src: &Path, dest: &Path, force: bool) -> anyhow::
match reflink_copy::reflink_or_copy(&src_path, &dest_path) {
Ok(_) => {}
Err(e) if e.kind() == ErrorKind::AlreadyExists => {}
- Err(e) => return Err(e.into()),
+ Err(e) => {
+ return Err(
+ anyhow::Error::from(e).context(format!("copying {}", src_path.display()))
+ );
+ }
}
}
}
@@ -833,6 +843,37 @@ fn copy_dir_recursive_fallback(src: &Path, dest: &Path, force: bool) -> anyhow::
Ok(())
}
+/// Create a symlink, handling platform differences.
+///
+/// On Windows, distinguishes between file and directory symlinks by checking the
+/// source path's metadata (the target may be relative or broken, so we use the
+/// source to determine the type).
+fn create_symlink(target: &Path, src_path: &Path, dest_path: &Path) -> anyhow::Result<()> {
+ #[cfg(unix)]
+ {
+ let _ = src_path; // Used on Windows to determine symlink type
+ std::os::unix::fs::symlink(target, dest_path)
+ .with_context(|| format!("creating symlink {}", dest_path.display()))?;
+ }
+ #[cfg(windows)]
+ {
+ 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)
+ .with_context(|| format!("creating symlink {}", dest_path.display()))?;
+ } else {
+ std::os::windows::fs::symlink_file(target, dest_path)
+ .with_context(|| format!("creating symlink {}", dest_path.display()))?;
+ }
+ }
+ #[cfg(not(any(unix, windows)))]
+ {
+ let _ = (target, src_path, dest_path);
+ anyhow::bail!("symlink creation not supported on this platform");
+ }
+ Ok(())
+}
+
/// Move worktrees to their expected paths based on the `worktree-path` template.
///
/// See `src/commands/relocate.rs` for the implementation details and algorithm.
diff --git a/tests/integration_tests/step_copy_ignored.rs b/tests/integration_tests/step_copy_ignored.rs
index 07c13a12a..72f75ada1 100644
--- a/tests/integration_tests/step_copy_ignored.rs
+++ b/tests/integration_tests/step_copy_ignored.rs
@@ -1,6 +1,6 @@
//! Integration tests for `wt step copy-ignored`
-use crate::common::{TestRepo, make_snapshot_cmd, repo};
+use crate::common::{TestRepo, make_snapshot_cmd, make_snapshot_cmd_with_global_flags, repo};
use insta_cmd::assert_cmd_snapshot;
use rstest::rstest;
use std::fs;
@@ -713,6 +713,240 @@ fn test_copy_ignored_force_directory(mut repo: TestRepo) {
);
}
+/// Test --verbose shows entries being copied (GitHub issue #1084)
+#[rstest]
+fn test_copy_ignored_verbose(mut repo: TestRepo) {
+ let feature_path = repo.add_worktree("feature");
+
+ // Create gitignored files
+ fs::write(repo.root_path().join(".env"), "SECRET=value").unwrap();
+ fs::write(repo.root_path().join(".gitignore"), ".env\n").unwrap();
+
+ // Run with -v (global verbose flag)
+ assert_cmd_snapshot!(make_snapshot_cmd_with_global_flags(
+ &repo,
+ "step",
+ &["copy-ignored"],
+ Some(&feature_path),
+ &["-v"],
+ ));
+
+ // Verify file was still copied
+ assert!(feature_path.join(".env").exists());
+}
+
+/// Test --verbose with directory entries (GitHub issue #1084)
+#[rstest]
+fn test_copy_ignored_verbose_directory(mut repo: TestRepo) {
+ let feature_path = repo.add_worktree("feature");
+
+ // Create target directory with files
+ let target_dir = repo.root_path().join("target");
+ fs::create_dir_all(target_dir.join("debug")).unwrap();
+ fs::write(target_dir.join("debug").join("output"), "binary").unwrap();
+ fs::write(repo.root_path().join(".gitignore"), "target/\n").unwrap();
+
+ assert_cmd_snapshot!(make_snapshot_cmd_with_global_flags(
+ &repo,
+ "step",
+ &["copy-ignored"],
+ Some(&feature_path),
+ &["-v"],
+ ));
+
+ assert!(
+ feature_path
+ .join("target")
+ .join("debug")
+ .join("output")
+ .exists()
+ );
+}
+
+/// Test idempotent behavior with broken symlinks after interrupted copy (GitHub issue #1084)
+///
+/// When ctrl+c interrupts a copy, broken symlinks may remain at the destination.
+/// exists() follows symlinks and returns false for broken ones, so a naive check
+/// would try to create a new symlink and fail with EEXIST.
+#[cfg(unix)]
+#[rstest]
+fn test_copy_ignored_broken_symlink_idempotent(mut repo: TestRepo) {
+ let feature_path = repo.add_worktree("feature");
+
+ // Create directory with a symlink in main
+ let target_dir = repo.root_path().join("target");
+ fs::create_dir_all(&target_dir).unwrap();
+ std::os::unix::fs::symlink("nonexistent", target_dir.join("link")).unwrap();
+
+ fs::write(repo.root_path().join(".gitignore"), "target/\n").unwrap();
+
+ // Simulate interrupted copy: create destination with a broken symlink
+ let dest_target = feature_path.join("target");
+ fs::create_dir_all(&dest_target).unwrap();
+ std::os::unix::fs::symlink("old_target", dest_target.join("link")).unwrap();
+
+ // Verify the broken symlink exists (symlink_metadata succeeds, but exists() returns false)
+ assert!(dest_target.join("link").symlink_metadata().is_ok());
+
+ // Run copy-ignored — should succeed (skip existing symlink), not fail with EEXIST
+ let output = repo
+ .wt_command()
+ .args(["step", "copy-ignored"])
+ .current_dir(&feature_path)
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "copy-ignored should succeed with broken symlink at destination: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+}
+
+/// Test that non-regular files (sockets) inside directories are skipped (GitHub issue #1084)
+///
+/// node_modules and similar directories can contain sockets or FIFOs.
+/// These should be silently skipped instead of failing with
+/// "source path is not an existing regular file".
+#[cfg(unix)]
+#[rstest]
+fn test_copy_ignored_skips_non_regular_files(mut repo: TestRepo) {
+ let feature_path = repo.add_worktree("feature");
+
+ // Create target directory with a socket and a regular file
+ let target_dir = repo.root_path().join("target");
+ fs::create_dir_all(&target_dir).unwrap();
+ let socket_path = target_dir.join("test.sock");
+ let _listener = std::os::unix::net::UnixListener::bind(&socket_path).unwrap();
+ fs::write(target_dir.join("data.txt"), "content").unwrap();
+
+ fs::write(repo.root_path().join(".gitignore"), "target/\n").unwrap();
+
+ // Should succeed, skipping the socket
+ let output = repo
+ .wt_command()
+ .args(["step", "copy-ignored"])
+ .current_dir(&feature_path)
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "copy-ignored should succeed with socket in directory: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ // Regular file should be copied, socket should NOT be copied
+ assert!(feature_path.join("target").join("data.txt").exists());
+ assert!(!feature_path.join("target").join("test.sock").exists());
+}
+
+/// Test that symlinks inside directories are copied correctly
+#[cfg(unix)]
+#[rstest]
+fn test_copy_ignored_directory_with_symlinks(mut repo: TestRepo) {
+ let feature_path = repo.add_worktree("feature");
+
+ // Create a gitignored directory containing a symlink
+ let target_dir = repo.root_path().join("target");
+ fs::create_dir_all(&target_dir).unwrap();
+ fs::write(target_dir.join("data.txt"), "content").unwrap();
+ std::os::unix::fs::symlink("data.txt", target_dir.join("link.txt")).unwrap();
+
+ fs::write(repo.root_path().join(".gitignore"), "target/\n").unwrap();
+
+ let output = repo
+ .wt_command()
+ .args(["step", "copy-ignored"])
+ .current_dir(&feature_path)
+ .output()
+ .unwrap();
+
+ assert!(output.status.success());
+
+ // Both the regular file and the symlink should be copied
+ assert!(feature_path.join("target").join("data.txt").exists());
+ let link = feature_path.join("target").join("link.txt");
+ assert!(link.symlink_metadata().unwrap().file_type().is_symlink());
+ assert_eq!(fs::read_link(&link).unwrap().to_str().unwrap(), "data.txt");
+}
+
+/// Test that copy errors include file paths in the message (GitHub issue #1084)
+///
+/// Tests both the directory recursive copy error path (copy_dir_recursive_fallback)
+/// and the top-level file copy error path (step_copy_ignored main loop).
+#[cfg(unix)]
+#[rstest]
+fn test_copy_ignored_error_includes_path_directory(mut repo: TestRepo) {
+ use std::os::unix::fs::PermissionsExt;
+
+ let feature_path = repo.add_worktree("feature");
+
+ // Create target directory with files
+ let target_dir = repo.root_path().join("target");
+ fs::create_dir_all(target_dir.join("sub")).unwrap();
+ fs::write(target_dir.join("sub").join("file.txt"), "content").unwrap();
+
+ fs::write(repo.root_path().join(".gitignore"), "target/\n").unwrap();
+
+ // Create destination target/sub as read-only so file copy fails
+ let dest_sub = feature_path.join("target").join("sub");
+ fs::create_dir_all(&dest_sub).unwrap();
+ fs::set_permissions(&dest_sub, fs::Permissions::from_mode(0o555)).unwrap();
+
+ // Copy should fail — error message should mention the file path
+ let output = repo
+ .wt_command()
+ .args(["step", "copy-ignored"])
+ .current_dir(&feature_path)
+ .output()
+ .unwrap();
+
+ // Restore permissions for cleanup
+ fs::set_permissions(&dest_sub, fs::Permissions::from_mode(0o755)).unwrap();
+
+ assert!(!output.status.success());
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("copying"),
+ "Error should mention the file path, got: {stderr}"
+ );
+}
+
+/// Test that top-level file copy errors include file paths (GitHub issue #1084)
+///
+/// This exercises the error path in the main copy loop (not copy_dir_recursive_fallback).
+#[cfg(unix)]
+#[rstest]
+fn test_copy_ignored_error_includes_path_file(mut repo: TestRepo) {
+ use std::os::unix::fs::PermissionsExt;
+
+ let feature_path = repo.add_worktree("feature");
+
+ // Create a top-level file that's gitignored
+ fs::write(repo.root_path().join(".env"), "SECRET=value").unwrap();
+ fs::write(repo.root_path().join(".gitignore"), ".env\n").unwrap();
+
+ // Make the destination worktree root read-only so reflink_or_copy fails
+ // with PermissionDenied (not AlreadyExists)
+ fs::set_permissions(&feature_path, fs::Permissions::from_mode(0o555)).unwrap();
+
+ let output = repo
+ .wt_command()
+ .args(["step", "copy-ignored"])
+ .current_dir(&feature_path)
+ .output()
+ .unwrap();
+
+ // Restore permissions for cleanup
+ fs::set_permissions(&feature_path, fs::Permissions::from_mode(0o755)).unwrap();
+
+ assert!(!output.status.success());
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("copying") && stderr.contains(".env"),
+ "Error should mention the file path, got: {stderr}"
+ );
+}
+
/// 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
diff --git a/tests/snapshots/integration__integration_tests__step_copy_ignored__copy_ignored_verbose.snap b/tests/snapshots/integration__integration_tests__step_copy_ignored__copy_ignored_verbose.snap
new file mode 100644
index 000000000..e352143c5
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__step_copy_ignored__copy_ignored_verbose.snap
@@ -0,0 +1,47 @@
+---
+source: tests/integration_tests/step_copy_ignored.rs
+info:
+ program: wt
+ args:
+ - "-v"
+ - 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
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ PATH: "[PATH]"
+ PSModulePath: ""
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+○ Copying 1 entry:
+  .env (file)
+✓ Copied 1 entry
diff --git a/tests/snapshots/integration__integration_tests__step_copy_ignored__copy_ignored_verbose_directory.snap b/tests/snapshots/integration__integration_tests__step_copy_ignored__copy_ignored_verbose_directory.snap
new file mode 100644
index 000000000..629374d7c
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__step_copy_ignored__copy_ignored_verbose_directory.snap
@@ -0,0 +1,47 @@
+---
+source: tests/integration_tests/step_copy_ignored.rs
+info:
+ program: wt
+ args:
+ - "-v"
+ - 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
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ PATH: "[PATH]"
+ PSModulePath: ""
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+○ Copying 1 entry:
+  target (dir)
+✓ Copied 1 entry