Skip to content

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

perf: parallelize copy-ignored with rayon (#1721)

worktrunk-bota0f461753518
diff --git a/benches/cow_copy.rs b/benches/cow_copy.rs
index af53461db..f40c456bf 100644
--- a/benches/cow_copy.rs
+++ b/benches/cow_copy.rs
@@ -1,23 +1,30 @@
// Benchmarks for `wt step copy-ignored` COW directory copying
//
-// Tests copy performance with realistic Rust target/ directory structures.
-// Uses file-by-file reflink copying on all platforms.
+// Compares serial vs the production parallel (rayon) recursive directory copying.
+// Two directory layouts test different parallelism profiles:
+//
+// - deep: Rust target/ with most files in a single deps/ dir (narrow tree)
+// - wide: Files spread across many subdirectories (wide tree)
//
// Run:
// cargo bench --bench cow_copy
+// cargo bench --bench cow_copy -- serial # serial only
+// cargo bench --bench cow_copy -- parallel # parallel only
+// cargo bench --bench cow_copy -- wide # wide tree only
use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main};
use std::path::Path;
use tempfile::TempDir;
+use worktrunk::copy::copy_dir_recursive;
-/// Create a directory structure mimicking a Rust target/ directory.
+/// Create a narrow directory structure mimicking a Rust target/ directory.
///
-/// Structure: target/debug/{deps,build,incremental}/... with .rlib, .rmeta, .d files
-fn create_target_dir(file_count: usize) -> TempDir {
+/// Most files concentrate in debug/deps/ — exercises parallelism within a single
+/// large directory.
+fn create_deep_target(file_count: usize) -> TempDir {
let temp = tempfile::tempdir().unwrap();
let target = temp.path().join("target");
- // Create typical Rust target subdirectories
let subdirs = [
"debug/deps",
"debug/build",
@@ -28,12 +35,10 @@ fn create_target_dir(file_count: usize) -> TempDir {
std::fs::create_dir_all(target.join(subdir)).unwrap();
}
- // Distribute files across subdirectories (mostly in deps/)
let mut created = 0;
let deps_dir = target.join("debug/deps");
while created < file_count {
- // Create .rlib files (larger, ~100KB simulated)
let rlib = deps_dir.join(format!("libcrate_{:04}.rlib", created));
std::fs::write(&rlib, vec![0u8; 100_000]).unwrap();
created += 1;
@@ -42,7 +47,6 @@ fn create_target_dir(file_count: usize) -> TempDir {
break;
}
- // Create .rmeta files (smaller, ~10KB)
let rmeta = deps_dir.join(format!("libcrate_{:04}.rmeta", created));
std::fs::write(&rmeta, vec![0u8; 10_000]).unwrap();
created += 1;
@@ -51,13 +55,11 @@ fn create_target_dir(file_count: usize) -> TempDir {
break;
}
- // Create .d dependency files (tiny, ~500 bytes)
let dep = deps_dir.join(format!("libcrate_{:04}.d", created));
std::fs::write(&dep, vec![0u8; 500]).unwrap();
created += 1;
}
- // Add some incremental compilation artifacts
let incr = target.join("debug/incremental/crate_name-hash");
std::fs::create_dir_all(&incr).unwrap();
for i in 0..10 {
@@ -67,16 +69,37 @@ fn create_target_dir(file_count: usize) -> TempDir {
temp
}
-/// Copy directory using the same approach as `wt step copy-ignored`.
+/// Create a wide directory tree with files distributed across many subdirectories.
///
-/// Uses file-by-file reflink on all platforms. We intentionally avoid atomic
-/// directory cloning on macOS (via clonefile()) because it saturates disk I/O
-/// and freezes interactive processes. See step_commands.rs for details.
-fn copy_dir_cow(src: &Path, dest: &Path) -> std::io::Result<()> {
- copy_dir_recursive(src, dest)
+/// Exercises parallelism across sibling directories — the primary benefit of
+/// rayon in copy_dir_recursive.
+fn create_wide_target(file_count: usize) -> TempDir {
+ let temp = tempfile::tempdir().unwrap();
+ let target = temp.path().join("target");
+
+ let files_per_dir = 10;
+ let dir_count = file_count / files_per_dir;
+ let mut created = 0;
+
+ for d in 0..dir_count {
+ let subdir = target.join(format!("pkg_{:04}", d));
+ std::fs::create_dir_all(&subdir).unwrap();
+
+ for f in 0..files_per_dir {
+ if created >= file_count {
+ return temp;
+ }
+ let file = subdir.join(format!("file_{:02}.dat", f));
+ std::fs::write(&file, vec![0u8; 50_000]).unwrap();
+ created += 1;
+ }
+ }
+
+ temp
}
-fn copy_dir_recursive(src: &Path, dest: &Path) -> std::io::Result<()> {
+/// Serial baseline: sequential file-by-file copy without rayon.
+fn copy_dir_serial(src: &Path, dest: &Path) -> std::io::Result<()> {
std::fs::create_dir_all(dest)?;
for entry in std::fs::read_dir(src)? {
let entry = entry?;
@@ -85,7 +108,7 @@ fn copy_dir_recursive(src: &Path, dest: &Path) -> std::io::Result<()> {
let dest_path = dest.join(entry.file_name());
if file_type.is_dir() {
- copy_dir_recursive(&src_path, &dest_path)?;
+ copy_dir_serial(&src_path, &dest_path)?;
} else if file_type.is_file() {
reflink_copy::reflink_or_copy(src_path, &dest_path)?;
}
@@ -93,23 +116,50 @@ fn copy_dir_recursive(src: &Path, dest: &Path) -> std::io::Result<()> {
Ok(())
}
-fn bench_copy_target(c: &mut Criterion) {
- let mut group = c.benchmark_group("copy_target");
-
- // Test various sizes typical of Rust projects
- for &file_count in &[100, 500, 1000, 2000] {
- let temp = create_target_dir(file_count);
- let src = temp.path().join("target");
+fn bench_helper(
+ group: &mut criterion::BenchmarkGroup<criterion::measurement::WallTime>,
+ label: &str,
+ file_count: usize,
+ create_fn: fn(usize) -> TempDir,
+) {
+ let temp = create_fn(file_count);
+ let src = temp.path().join("target");
+
+ group.bench_with_input(
+ BenchmarkId::new(format!("serial/{label}"), file_count),
+ &src,
+ |b, src| {
+ let mut iter = 0u64;
+ b.iter(|| {
+ let dest = temp.path().join(format!("copy_s_{}", iter));
+ iter += 1;
+ copy_dir_serial(src, &dest).unwrap();
+ std::fs::remove_dir_all(&dest).ok();
+ });
+ },
+ );
- group.bench_with_input(BenchmarkId::new("files", file_count), &src, |b, src| {
+ group.bench_with_input(
+ BenchmarkId::new(format!("parallel/{label}"), file_count),
+ &src,
+ |b, src| {
let mut iter = 0u64;
b.iter(|| {
- let dest = temp.path().join(format!("target_copy_{}", iter));
+ let dest = temp.path().join(format!("copy_p_{}", iter));
iter += 1;
- copy_dir_cow(src, &dest).unwrap();
+ copy_dir_recursive(src, &dest, false).unwrap();
std::fs::remove_dir_all(&dest).ok();
});
- });
+ },
+ );
+}
+
+fn bench_copy_target(c: &mut Criterion) {
+ let mut group = c.benchmark_group("copy_target");
+
+ for &file_count in &[100, 500, 1000] {
+ bench_helper(&mut group, "deep", file_count, create_deep_target);
+ bench_helper(&mut group, "wide", file_count, create_wide_target);
}
group.finish();
diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rs
index 80885464e..415521dca 100644
--- a/src/commands/step_commands.rs
+++ b/src/commands/step_commands.rs
@@ -15,15 +15,19 @@
use std::fs;
use std::io::ErrorKind;
use std::path::{Path, PathBuf};
+use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
use anyhow::Context;
use color_print::cformat;
use ignore::gitignore::GitignoreBuilder;
+use rayon::prelude::*;
use worktrunk::HookType;
use worktrunk::config::{CopyIgnoredConfig, UserConfig};
+use worktrunk::copy::{copy_dir_recursive, create_symlink, remove_if_exists};
use worktrunk::git::Repository;
use worktrunk::path::format_path_for_display;
+use worktrunk::shell_exec::Cmd;
use worktrunk::styling::{
eprintln, format_with_gutter, hint_message, info_message, progress_message, success_message,
verbosity, warning_message,
@@ -39,7 +43,6 @@ use super::hooks::{
use super::repository_ext::{RemoveTarget, RepositoryCliExt};
use super::worktree::BranchDeletionMode;
use crate::output::handle_remove_output;
-use worktrunk::shell_exec::Cmd;
/// Handle `wt step commit` command
///
@@ -764,7 +767,7 @@ pub fn step_copy_ignored(
}
let verbose = verbosity();
- let mut copied_count = 0;
+ let copied_count = AtomicUsize::new(0);
// Show entries in verbose or dry-run mode
if verbose >= 1 || dry_run {
@@ -794,66 +797,71 @@ pub fn step_copy_ignored(
}
}
- // Copy entries
- for (src_entry, is_dir) in &entries_to_copy {
- // Paths from git ls-files are always under source_path
- let relative = src_entry
- .strip_prefix(&source_path)
- .expect("git ls-files path under worktree");
- let dest_entry = dest_path.join(relative);
-
- if *is_dir {
- copy_dir_recursive(src_entry, &dest_entry, force).with_context(|| {
- format!("copying directory {}", format_path_for_display(relative))
- })?;
- copied_count += 1;
- } else {
- if let Some(parent) = dest_entry.parent() {
- fs::create_dir_all(parent).with_context(|| {
- format!(
- "creating directory for {}",
- format_path_for_display(relative)
- )
+ // Copy entries in parallel — each entry has a distinct destination path
+ entries_to_copy
+ .par_iter()
+ .try_for_each(|(src_entry, is_dir)| -> anyhow::Result<()> {
+ // Paths from git ls-files are always under source_path
+ let relative = src_entry
+ .strip_prefix(&source_path)
+ .expect("git ls-files path under worktree");
+ let dest_entry = dest_path.join(relative);
+
+ if *is_dir {
+ copy_dir_recursive(src_entry, &dest_entry, force).with_context(|| {
+ format!("copying directory {}", format_path_for_display(relative))
})?;
- }
- if force {
- remove_if_exists(&dest_entry)?;
- }
- // Check if source is a symlink — preserve it instead of following it
- let display_path = format_path_for_display(relative);
- let source_is_symlink = fs::symlink_metadata(src_entry)
- .context(format!("reading metadata for {display_path}"))?
- .file_type()
- .is_symlink();
- if source_is_symlink {
- // Skip existing symlinks for idempotent hook usage
- if dest_entry.symlink_metadata().is_err() {
- let target = fs::read_link(src_entry)
- .context(format!("reading symlink {display_path}"))?;
- create_symlink(&target, src_entry, &dest_entry)?;
- copied_count += 1;
- }
+ copied_count.fetch_add(1, Ordering::Relaxed);
} else {
- // Skip existing entries (files or symlinks) for idempotent hook usage.
- // Check symlink_metadata (not exists()) because exists() follows symlinks
- // and returns false for broken ones, which would cause reflink_or_copy to
- // fail with ENOENT on some platforms when copying through the broken symlink.
- if dest_entry.symlink_metadata().is_err() {
- 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(
- anyhow::Error::from(e).context(format!("copying {display_path}"))
- );
+ if let Some(parent) = dest_entry.parent() {
+ fs::create_dir_all(parent).with_context(|| {
+ format!(
+ "creating directory for {}",
+ format_path_for_display(relative)
+ )
+ })?;
+ }
+ if force {
+ remove_if_exists(&dest_entry)?;
+ }
+ // Check if source is a symlink — preserve it instead of following it
+ let display_path = format_path_for_display(relative);
+ let source_is_symlink = fs::symlink_metadata(src_entry)
+ .context(format!("reading metadata for {display_path}"))?
+ .file_type()
+ .is_symlink();
+ if source_is_symlink {
+ // Skip existing symlinks for idempotent hook usage
+ if dest_entry.symlink_metadata().is_err() {
+ let target = fs::read_link(src_entry)
+ .context(format!("reading symlink {display_path}"))?;
+ create_symlink(&target, src_entry, &dest_entry)?;
+ copied_count.fetch_add(1, Ordering::Relaxed);
+ }
+ } else {
+ // Skip existing entries (files or symlinks) for idempotent hook usage.
+ // Check symlink_metadata (not exists()) because exists() follows symlinks
+ // and returns false for broken ones, which would cause reflink_or_copy to
+ // fail with ENOENT on some platforms when copying through the broken symlink.
+ if dest_entry.symlink_metadata().is_err() {
+ match reflink_copy::reflink_or_copy(src_entry, &dest_entry) {
+ Ok(_) => {
+ copied_count.fetch_add(1, Ordering::Relaxed);
+ }
+ Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
+ Err(e) => {
+ return Err(anyhow::Error::from(e)
+ .context(format!("copying {display_path}")));
+ }
}
}
}
}
- }
- }
+ Ok(())
+ })?;
// Show summary
+ let copied_count = copied_count.load(Ordering::Relaxed);
let entry_word = if copied_count == 1 {
"entry"
} else {
@@ -867,14 +875,6 @@ pub fn step_copy_ignored(
Ok(())
}
-/// Remove a file, ignoring "not found" errors.
-fn remove_if_exists(path: &Path) -> anyhow::Result<()> {
- if let Err(e) = fs::remove_file(path) {
- anyhow::ensure!(e.kind() == ErrorKind::NotFound, e);
- }
- Ok(())
-}
-
/// List ignored entries using git ls-files
///
/// Uses `git ls-files --ignored --exclude-standard -o --directory` which:
@@ -915,96 +915,6 @@ fn list_ignored_entries(
Ok(entries)
}
-/// Copy a directory recursively using reflink (COW).
-///
-/// Uses file-by-file copying with per-file reflink on all platforms. This spreads
-/// I/O operations over time rather than issuing them in a single burst.
-///
-/// ## Why not use atomic directory cloning on macOS?
-///
-/// macOS/APFS supports `clonefile()` on directories, which clones an entire tree
-/// atomically. However, Apple explicitly discourages this in the man page:
-///
-/// > "Cloning directories with these functions is strongly discouraged.
-/// > Use copyfile(3) to clone directories instead."
-/// > — clonefile(2) man page
-///
-/// In practice, atomic `clonefile()` on a Rust `target/` directory (~236K files)
-/// saturates disk I/O at ~45K ops/sec, blocking interactive processes like shell
-/// startup for several seconds. The per-file approach spreads operations over
-/// time, keeping the system responsive even though total copy time is longer.
-///
-/// Apple recommends `copyfile()` with `COPYFILE_CLONE` for directories, which
-/// internally walks the tree and clones per-file — equivalent to what we do here.
-fn copy_dir_recursive(src: &Path, dest: &Path, force: bool) -> anyhow::Result<()> {
- copy_dir_recursive_fallback(src, dest, force)
-}
-
-/// File-by-file recursive copy with reflink per file.
-///
-/// 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).with_context(|| format!("creating directory {}", dest.display()))?;
-
- for entry in fs::read_dir(src)? {
- let entry = entry?;
- let file_type = entry.file_type()?;
- let src_path = entry.path();
- let dest_path = dest.join(entry.file_name());
-
- if file_type.is_symlink() {
- // Copy symlink (preserves the link, doesn't follow it)
- if force {
- remove_if_exists(&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)?;
- }
- // Skip existing entries (files or symlinks) for idempotent hook usage.
- // Check symlink_metadata (not exists()) because exists() follows symlinks
- // and returns false for broken ones, which would cause reflink_or_copy to
- // fail with ENOENT on some platforms when copying through the broken symlink.
- if dest_path.symlink_metadata().is_err() {
- match reflink_copy::reflink_or_copy(&src_path, &dest_path) {
- Ok(_) => {}
- Err(e) if e.kind() == ErrorKind::AlreadyExists => {}
- Err(e) => {
- return Err(anyhow::Error::from(e)
- .context(format!("copying {}", src_path.display())));
- }
- }
- }
- }
- }
-
- // Preserve source directory permissions AFTER copying contents.
- // Must be done after the loop — if the source lacks write permission (e.g., 0o555),
- // setting it before copying would make the destination read-only and fail the copies.
- #[cfg(unix)]
- {
- let src_perms = fs::metadata(src)
- .with_context(|| format!("reading permissions for {}", src.display()))?
- .permissions();
- fs::set_permissions(dest, src_perms)
- .with_context(|| format!("setting permissions on {}", dest.display()))?;
- }
-
- Ok(())
-}
-
/// Move a file or directory, falling back to copy+delete on cross-device errors.
fn move_entry(src: &Path, dest: &Path, is_dir: bool) -> anyhow::Result<()> {
// Ensure parent directory exists
@@ -1381,37 +1291,6 @@ pub fn handle_promote(branch: Option<&str>) -> anyhow::Result<PromoteResult> {
Ok(PromoteResult::Promoted)
}
-/// 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(())
-}
-
/// Remove worktrees and branches integrated into the default branch.
///
/// Handles four cases: live worktrees with branches (removed + branch deleted),
diff --git a/src/copy.rs b/src/copy.rs
new file mode 100644
index 000000000..f3794cf18
--- /dev/null
+++ b/src/copy.rs
@@ -0,0 +1,138 @@
+//! Recursive directory copying with reflink (COW) and rayon parallelism.
+//!
+//! Copies directory trees file-by-file using `reflink_or_copy` which uses
+//! copy-on-write clones where the filesystem supports them (APFS, btrfs, XFS),
+//! falling back to regular copies otherwise.
+//!
+//! Parallelism is achieved with rayon's `par_iter` at each directory level,
+//! so sibling entries are copied concurrently while the tree is walked
+//! depth-first.
+
+use std::fs;
+use std::io::ErrorKind;
+use std::path::Path;
+
+use anyhow::Context;
+use rayon::prelude::*;
+
+/// Maximum threads for filesystem copy operations. Beyond this, SSD I/O
+/// contention causes performance to regress (benchmarked on APFS and ext4).
+/// The global rayon pool is sized for network I/O (2x cores) which is too
+/// many for local filesystem work.
+const MAX_COPY_THREADS: usize = 4;
+
+/// Copy a directory tree recursively using reflink (COW) per file.
+///
+/// Handles regular files, directories, and symlinks. Non-regular files (sockets,
+/// FIFOs) are silently skipped. Existing entries at the destination are skipped
+/// for idempotent usage.
+///
+/// When `force` is true, existing files and symlinks at the destination are
+/// removed before copying.
+///
+/// Uses a dedicated rayon thread pool capped at `MAX_COPY_THREADS` to avoid
+/// SSD I/O contention from the larger global pool.
+pub fn copy_dir_recursive(src: &Path, dest: &Path, force: bool) -> anyhow::Result<()> {
+ let pool = rayon::ThreadPoolBuilder::new()
+ .num_threads(MAX_COPY_THREADS)
+ .build()
+ .context("building copy thread pool")?;
+
+ pool.install(|| copy_dir_recursive_inner(src, dest, force))
+}
+
+fn copy_dir_recursive_inner(src: &Path, dest: &Path, force: bool) -> anyhow::Result<()> {
+ fs::create_dir_all(dest).with_context(|| format!("creating directory {}", dest.display()))?;
+
+ let entries: Vec<_> = fs::read_dir(src)?.collect::<Result<Vec<_>, _>>()?;
+
+ entries.into_par_iter().try_for_each(|entry| {
+ let file_type = entry.file_type()?;
+ let src_path = entry.path();
+ let dest_path = dest.join(entry.file_name());
+
+ if file_type.is_symlink() {
+ if force {
+ remove_if_exists(&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_inner(&src_path, &dest_path, force)?;
+ } else if !file_type.is_file() {
+ log::debug!("skipping non-regular file: {}", src_path.display());
+ } else {
+ if force {
+ remove_if_exists(&dest_path)?;
+ }
+ // Check symlink_metadata (not exists()) because exists() follows symlinks
+ // and returns false for broken ones, which would cause reflink_or_copy to
+ // fail with ENOENT on some platforms when copying through the broken symlink.
+ if dest_path.symlink_metadata().is_err() {
+ match reflink_copy::reflink_or_copy(&src_path, &dest_path) {
+ Ok(_) => {}
+ Err(e) if e.kind() == ErrorKind::AlreadyExists => {}
+ Err(e) => {
+ return Err(anyhow::Error::from(e)
+ .context(format!("copying {}", src_path.display())));
+ }
+ }
+ }
+ }
+ Ok(())
+ })?;
+
+ // Preserve source directory permissions AFTER copying contents.
+ // Must be done after the loop — if the source lacks write permission (e.g., 0o555),
+ // setting it before copying would make the destination read-only and fail the copies.
+ #[cfg(unix)]
+ {
+ let src_perms = fs::metadata(src)
+ .with_context(|| format!("reading permissions for {}", src.display()))?
+ .permissions();
+ fs::set_permissions(dest, src_perms)
+ .with_context(|| format!("setting permissions on {}", dest.display()))?;
+ }
+
+ Ok(())
+}
+
+/// Remove a file, ignoring "not found" errors.
+pub fn remove_if_exists(path: &Path) -> anyhow::Result<()> {
+ if let Err(e) = fs::remove_file(path) {
+ anyhow::ensure!(e.kind() == ErrorKind::NotFound, e);
+ }
+ Ok(())
+}
+
+/// Create a symlink, handling platform differences.
+pub 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(())
+}
diff --git a/src/lib.rs b/src/lib.rs
index 8e866b5d8..c8919e3c7 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -9,6 +9,7 @@
pub mod command_log;
pub mod config;
+pub mod copy;
pub mod git;
pub mod path;
pub mod shell;
diff --git a/tests/integration_tests/step_copy_ignored.rs b/tests/integration_tests/step_copy_ignored.rs
index 4738214b3..fec170517 100644
--- a/tests/integration_tests/step_copy_ignored.rs
+++ b/tests/integration_tests/step_copy_ignored.rs
@@ -1080,6 +1080,52 @@ fn test_copy_ignored_error_includes_path_file(mut repo: TestRepo) {
);
}
+/// Test that nested file copy errors mention the parent directory creation failure
+///
+/// Exercises the `create_dir_all(parent)` error path in the top-level file copy loop.
+/// The existing `test_copy_ignored_error_includes_path_file` test uses a top-level file,
+/// so it doesn't reach `create_dir_all`.
+#[cfg(unix)]
+#[rstest]
+fn test_copy_ignored_error_nested_file_parent_creation(mut repo: TestRepo) {
+ use std::os::unix::fs::PermissionsExt;
+
+ let feature_path = repo.add_worktree("feature");
+
+ // Create a nested file that's individually gitignored (not as a directory)
+ let cache_dir = repo.root_path().join("cache");
+ fs::create_dir_all(&cache_dir).unwrap();
+ fs::write(cache_dir.join("data.json"), "content").unwrap();
+
+ // Gitignore the specific file (not the directory) so git ls-files returns it as a file
+ fs::write(repo.root_path().join(".gitignore"), "cache/data.json\n").unwrap();
+ fs::write(
+ repo.root_path().join(".worktreeinclude"),
+ "cache/data.json\n",
+ )
+ .unwrap();
+
+ // Make feature worktree root read-only so create_dir_all("cache/") fails
+ 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("creating directory for") && stderr.contains("cache"),
+ "Error should mention parent directory creation, got: {stderr}"
+ );
+}
+
/// Test that broken symlinks at the destination don't prevent copying regular files (GitHub #1547)
///
/// When copy-ignored runs and the destination already has a broken symlink where a