Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat: add `--force` flag to `wt step copy-ignored` (#974)
Maximilian Roosd29e4e66b85d
diff --git a/.claude-plugin/skills/worktrunk/reference/step.md b/.claude-plugin/skills/worktrunk/reference/step.mdindex 256562b03..b0dad7baf 100644--- a/.claude-plugin/skills/worktrunk/reference/step.md+++ b/.claude-plugin/skills/worktrunk/reference/step.md@@ -270,7 +270,8 @@ target/- 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 existing files by default (safe to re-run)+- `--force` overwrites existing files in the destination- Skips `.git` entries and other worktrees### Performance@@ -335,6 +336,9 @@ Usage: <b><span class=c>wt step copy-ignored</span></b> <span class=c>[OPTIONS]<<b><span class=c>--dry-run</span></b>Show what would be copied+ <b><span class=c>--force</span></b>+ Overwrite existing files in destination+<b><span class=c>-h</span></b>, <b><span class=c>--help</span></b>Print help (see a summary with '-h')diff --git a/docs/content/step.md b/docs/content/step.mdindex 46f04e9f8..eb8c5ac48 100644--- a/docs/content/step.md+++ b/docs/content/step.md@@ -289,7 +289,8 @@ target/- 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 existing files by default (safe to re-run)+- `--force` overwrites existing files in the destination- Skips `.git` entries and other worktrees### Performance@@ -355,6 +356,9 @@ Usage: <b><span class=c>wt step copy-ignored</span></b> <span class=c>[OPTIONS]<<b><span class=c>--dry-run</span></b>Show what would be copied+ <b><span class=c>--force</span></b>+ Overwrite existing files in destination+<b><span class=c>-h</span></b>, <b><span class=c>--help</span></b>Print help (see a summary with '-h')diff --git a/src/cli/step.rs b/src/cli/step.rsindex d9843376c..f33dccb2e 100644--- a/src/cli/step.rs+++ b/src/cli/step.rs@@ -211,7 +211,8 @@ target/- 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 existing files by default (safe to re-run)+- `--force` overwrites existing files in the destination- Skips `.git` entries and other worktrees## Performance@@ -271,6 +272,10 @@ The `.worktreeinclude` pattern is shared with [Claude Code on desktop](https://c/// Show what would be copied#[arg(long)]dry_run: bool,++ /// Overwrite existing files in destination+ #[arg(long)]+ force: bool,},/// \[experimental\] Run command in each worktreediff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rsindex 0a79ded90..c88b5c252 100644--- a/src/commands/step_commands.rs+++ b/src/commands/step_commands.rs@@ -481,6 +481,7 @@ pub fn step_copy_ignored(from: Option<&str>,to: Option<&str>,dry_run: bool,+ force: bool,) -> anyhow::Result<()> {let repo = Repository::current()?;@@ -612,12 +613,15 @@ pub fn step_copy_ignored(let dest_entry = dest_path.join(relative);if *is_dir {- copy_dir_recursive(src_entry, &dest_entry)?;+ copy_dir_recursive(src_entry, &dest_entry, force)?;copied_count += 1;} else {if let Some(parent) = dest_entry.parent() {fs::create_dir_all(parent)?;}+ if force {+ remove_if_exists(&dest_entry)?;+ }// Skip existing files for idempotent hook usagematch reflink_copy::reflink_or_copy(src_entry, &dest_entry) {Ok(_) => copied_count += 1,@@ -641,6 +645,14 @@ 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:@@ -702,14 +714,14 @@ fn list_ignored_entries(////// 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) -> anyhow::Result<()> {- copy_dir_recursive_fallback(src, dest)+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) -> anyhow::Result<()> {+fn copy_dir_recursive_fallback(src: &Path, dest: &Path, force: bool) -> anyhow::Result<()> {fs::create_dir_all(dest)?;for entry in fs::read_dir(src)? {@@ -720,6 +732,9 @@ fn copy_dir_recursive_fallback(src: &Path, dest: &Path) -> anyhow::Result<()> {if file_type.is_symlink() {// Copy symlink (preserves the link, doesn't follow it)+ if force {+ remove_if_exists(&dest_path)?;+ }if !dest_path.exists() {let target = fs::read_link(&src_path)?;#[cfg(unix)]@@ -736,8 +751,11 @@ fn copy_dir_recursive_fallback(src: &Path, dest: &Path) -> anyhow::Result<()> {}}} else if file_type.is_dir() {- copy_dir_recursive_fallback(&src_path, &dest_path)?;+ copy_dir_recursive_fallback(&src_path, &dest_path, force)?;} else {+ if force {+ remove_if_exists(&dest_path)?;+ }// Skip existing files for idempotent hook usagematch reflink_copy::reflink_or_copy(&src_path, &dest_path) {Ok(_) => {}@@ -867,4 +885,17 @@ mod tests {panic!("Expected UpToDate variant");}}++ #[test]+ fn test_remove_if_exists_nonexistent() {+ // NotFound is silently ignored+ assert!(remove_if_exists(Path::new("/nonexistent/file")).is_ok());+ }++ #[test]+ fn test_remove_if_exists_not_a_file() {+ // Trying to remove a directory with remove_file produces a non-NotFound error+ let dir = std::env::temp_dir();+ assert!(remove_if_exists(&dir).is_err());+ }}diff --git a/src/main.rs b/src/main.rsindex c867d0aea..7d9ea1d75 100644--- a/src/main.rs+++ b/src/main.rs@@ -534,9 +534,12 @@ fn main() {}})}- StepCommand::CopyIgnored { from, to, dry_run } => {- step_copy_ignored(from.as_deref(), to.as_deref(), dry_run)- }+ StepCommand::CopyIgnored {+ from,+ to,+ dry_run,+ force,+ } => step_copy_ignored(from.as_deref(), to.as_deref(), dry_run, force),StepCommand::ForEach { args } => step_for_each(args),StepCommand::Relocate {branches,diff --git a/tests/integration_tests/step_copy_ignored.rs b/tests/integration_tests/step_copy_ignored.rsindex 897add192..07c13a12a 100644--- a/tests/integration_tests/step_copy_ignored.rs+++ b/tests/integration_tests/step_copy_ignored.rs@@ -601,6 +601,118 @@ fn test_copy_ignored_bare_repo() {);}+/// Test --force overwrites existing files in destination+#[rstest]+fn test_copy_ignored_force_overwrites(mut repo: TestRepo) {+ let feature_path = repo.add_worktree("feature");++ // Create .env in main with original content+ fs::write(repo.root_path().join(".env"), "NEW_SECRET=updated").unwrap();+ fs::write(repo.root_path().join(".gitignore"), ".env\n").unwrap();+ fs::write(repo.root_path().join(".worktreeinclude"), ".env\n").unwrap();++ // Create existing .env in feature with different content (e.g., generated by env:setup)+ fs::write(feature_path.join(".env"), "OLD_SECRET=stale").unwrap();++ // Without --force: existing file should NOT be overwritten+ repo.wt_command()+ .args(["step", "copy-ignored"])+ .current_dir(&feature_path)+ .output()+ .unwrap();+ assert_eq!(+ fs::read_to_string(feature_path.join(".env")).unwrap(),+ "OLD_SECRET=stale",+ "Without --force, existing file should not be overwritten"+ );++ // With --force: existing file SHOULD be overwritten+ assert_cmd_snapshot!(make_snapshot_cmd(+ &repo,+ "step",+ &["copy-ignored", "--force"],+ Some(&feature_path),+ ));+ assert_eq!(+ fs::read_to_string(feature_path.join(".env")).unwrap(),+ "NEW_SECRET=updated",+ "With --force, existing file should be overwritten"+ );+}++/// Test --force works when destination file doesn't exist yet (no-op removal)+#[rstest]+fn test_copy_ignored_force_no_existing(mut repo: TestRepo) {+ let feature_path = repo.add_worktree("feature");++ // Create .env in main only — feature has no .env+ fs::write(repo.root_path().join(".env"), "SECRET=value").unwrap();+ fs::write(repo.root_path().join(".gitignore"), ".env\n").unwrap();+ fs::write(repo.root_path().join(".worktreeinclude"), ".env\n").unwrap();++ // --force on a fresh worktree should still copy successfully+ assert_cmd_snapshot!(make_snapshot_cmd(+ &repo,+ "step",+ &["copy-ignored", "--force"],+ Some(&feature_path),+ ));+ assert_eq!(+ fs::read_to_string(feature_path.join(".env")).unwrap(),+ "SECRET=value",+ "With --force, file should be copied even when dest doesn't exist"+ );+}++/// Test --force overwrites files and symlinks inside directories+#[rstest]+fn test_copy_ignored_force_directory(mut repo: TestRepo) {+ let feature_path = repo.add_worktree("feature");++ // Create target directory with a file and a symlink in main+ 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"), "new content").unwrap();+ #[cfg(unix)]+ std::os::unix::fs::symlink("output", target_dir.join("debug").join("link")).unwrap();++ fs::write(repo.root_path().join(".gitignore"), "target/\n").unwrap();+ fs::write(repo.root_path().join(".worktreeinclude"), "target/\n").unwrap();++ // Create existing file and symlink in feature with different content/target+ fs::create_dir_all(feature_path.join("target").join("debug")).unwrap();+ fs::write(+ feature_path.join("target").join("debug").join("output"),+ "old content",+ )+ .unwrap();+ #[cfg(unix)]+ std::os::unix::fs::symlink(+ "old_target",+ feature_path.join("target").join("debug").join("link"),+ )+ .unwrap();++ // With --force: files and symlinks inside directory should be overwritten+ repo.wt_command()+ .args(["step", "copy-ignored", "--force"])+ .current_dir(&feature_path)+ .output()+ .unwrap();++ assert_eq!(+ fs::read_to_string(feature_path.join("target").join("debug").join("output")).unwrap(),+ "new content",+ "With --force, files inside directories should be overwritten"+ );+ #[cfg(unix)]+ assert_eq!(+ fs::read_link(feature_path.join("target").join("debug").join("link")).unwrap(),+ std::path::PathBuf::from("output"),+ "With --force, symlinks inside directories should be overwritten"+ );+}+/// Test that worktrees nested inside the source are not copied (GitHub issue #641)////// When worktree-path is configured to place worktrees inside the primary worktreediff --git a/tests/snapshots/integration__integration_tests__step_copy_ignored__copy_ignored_force_no_existing.snap b/tests/snapshots/integration__integration_tests__step_copy_ignored__copy_ignored_force_no_existing.snapnew file mode 100644index 000000000..dc4dccc9d--- /dev/null+++ b/tests/snapshots/integration__integration_tests__step_copy_ignored__copy_ignored_force_no_existing.snap@@ -0,0 +1,42 @@+---+source: tests/integration_tests/step_copy_ignored.rs+info:+ program: wt+ args:+ - step+ - copy-ignored+ - "--force"+ 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_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ WT_TEST_DELAYED_STREAM_MS: "-1"+ WT_TEST_EPOCH: "1735776000"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----++----- stderr -----+[32m✓[39m [32mCopied 1 entry[39mdiff --git a/tests/snapshots/integration__integration_tests__step_copy_ignored__copy_ignored_force_overwrites.snap b/tests/snapshots/integration__integration_tests__step_copy_ignored__copy_ignored_force_overwrites.snapnew file mode 100644index 000000000..dc4dccc9d--- /dev/null+++ b/tests/snapshots/integration__integration_tests__step_copy_ignored__copy_ignored_force_overwrites.snap@@ -0,0 +1,42 @@+---+source: tests/integration_tests/step_copy_ignored.rs+info:+ program: wt+ args:+ - step+ - copy-ignored+ - "--force"+ 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_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ WT_TEST_DELAYED_STREAM_MS: "-1"+ WT_TEST_EPOCH: "1735776000"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----++----- stderr -----+[32m✓[39m [32mCopied 1 entry[39m