Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Refactor `dev-detach` helper binary for tests
Maximilian Roos5f46aa548b75
diff --git a/Cargo.lock b/Cargo.lockindex 177c031d9..86a9da90c 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -686,13 +686,6 @@ dependencies = ["syn",]-[[package]]-name = "dev-detach"-version = "0.1.0"-dependencies = [- "nix 0.30.1",-]-[[package]]name = "digest"version = "0.10.7"@@ -897,16 +890,6 @@ version = "0.1.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"-[[package]]-name = "fs2"-version = "0.4.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9564fc758e15025b46aa6643b1b77d047d1a56a1aea6e01002ac0c7026876213"-dependencies = [- "libc",- "winapi",-]-[[package]]name = "futures-core"version = "0.3.31"@@ -2907,13 +2890,13 @@ dependencies = ["crossterm","env_logger","etcetera",- "fs2","home","indexmap","insta","insta-cmd","log","minijinja",+ "nix 0.30.1","osc8","portable-pty","rayon",diff --git a/Cargo.toml b/Cargo.tomlindex 91ca2c6ac..cd1c5b3d4 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -1,5 +1,5 @@[workspace]-members = ["tests/helpers/dev-detach", "tests/helpers/setup-select-test"]+members = ["tests/helpers/setup-select-test"][package]name = "worktrunk"@@ -25,7 +25,8 @@ consolidate-commits = truedefault = ["syntax-highlighting"]syntax-highlighting = ["dep:tree-sitter", "dep:tree-sitter-bash", "dep:tree-sitter-highlight"]# Enable shell integration tests (requires bash, zsh, fish installed on system)-shell-integration-tests = []+# Also builds dev-detach helper binary for TTY isolation+shell-integration-tests = ["dep:nix"][lib]name = "worktrunk"@@ -35,6 +36,13 @@ path = "src/lib.rs"name = "wt"path = "src/main.rs"+# Test helper for TTY isolation in shell integration tests (Unix only)+# Excluded from `cargo install` via required-features+[[bin]]+name = "dev-detach"+path = "src/bin/dev-detach.rs"+required-features = ["shell-integration-tests"]+[dependencies]anyhow = "1.0"anstream = "0.6"@@ -75,6 +83,8 @@ home = "0.5.12"[target.'cfg(unix)'.dependencies]skim = "0.20"+# Used by dev-detach binary for TTY isolation in shell integration tests (optional)+nix = { version = "0.30", default-features = false, features = ["process"], optional = true }[build-dependencies]vergen-gitcl = { version = "1.0.8", features = ["build"] }@@ -89,7 +99,6 @@ criterion = "0.7"portable-pty = "0.9"regex = "1.12"vt100 = "0.16"-fs2 = "0.4"[[bench]]name = "completion"diff --git a/src/bin/dev-detach.rs b/src/bin/dev-detach.rsnew file mode 100644index 000000000..9888901c9--- /dev/null+++ b/src/bin/dev-detach.rs@@ -0,0 +1,53 @@+//! Test helper for TTY isolation in shell integration tests.+//!+//! Detaches child processes from controlling terminals by calling setsid()+//! before exec'ing the target command. Prevents PTY-related hangs when running+//! nextest in environments like unbuffer or script.+//!+//! Usage: dev-detach \<command\> [args...]++use std::{env, process};++fn main() {+ #[cfg(unix)]+ {+ use nix::unistd::{execvp, setsid};+ use std::ffi::CString;++ if let Err(e) = setsid() {+ eprintln!("dev-detach: setsid failed: {e}");+ process::exit(1);+ }++ let args: Vec<String> = env::args().skip(1).collect();+ if args.is_empty() {+ eprintln!("usage: dev-detach <command> [args...]");+ process::exit(2);+ }++ let prog = CString::new(args[0].clone()).unwrap_or_else(|_| {+ eprintln!("dev-detach: command contains null byte");+ process::exit(2);+ });+ let cargs: Vec<CString> = args+ .iter()+ .map(|a| {+ CString::new(a.as_str()).unwrap_or_else(|_| {+ eprintln!("dev-detach: argument contains null byte");+ process::exit(2);+ })+ })+ .collect();++ // execvp only returns on error (success replaces this process)+ let Err(e) = execvp(prog.as_c_str(), &cargs);+ eprintln!("dev-detach: execvp failed: {e}");+ process::exit(127);+ }++ #[cfg(not(unix))]+ {+ eprintln!("dev-detach is Unix-only (used for TTY isolation in tests)");+ process::exit(1);+ }+}diff --git a/tests/common/mod.rs b/tests/common/mod.rsindex b9fa2cefc..a7e188a47 100644--- a/tests/common/mod.rs+++ b/tests/common/mod.rs@@ -27,6 +27,7 @@pub mod list_snapshots;pub mod progressive_output;+#[cfg(feature = "shell-integration-tests")]pub mod shell;use insta_cmd::get_cargo_bin;diff --git a/tests/common/shell.rs b/tests/common/shell.rsindex 26e291c10..c7108cf5d 100644--- a/tests/common/shell.rs+++ b/tests/common/shell.rs@@ -1,58 +1,9 @@use super::{TestRepo, wt_command};-use fs2::FileExt;use insta_cmd::get_cargo_bin;-use std::fs::OpenOptions;-use std::path::PathBuf;use std::process::Command;-/// Get path to dev-detach binary, building it once if needed.-///-/// Uses file locking to ensure only one concurrent build across test processes.-/// This prevents cargo lock contention that was causing SIGKILL failures when-/// multiple test processes invoked `cargo run -p dev-detach` simultaneously.-///-/// The lock prevents concurrent builds but does not protect against the binary-/// being deleted after the lock is released. In practice, this is not an issue-/// in the test environment.-fn get_dev_detach_bin() -> PathBuf {- let manifest_dir = std::env::current_dir().unwrap();- let bin_path = manifest_dir.join("target/debug/dev-detach");-- // Lock file ensures only one process builds at a time- let lock_path = manifest_dir.join("target/.dev-detach.lock");- let lock_file = OpenOptions::new()- .create(true)- .truncate(false)- .write(true)- .open(&lock_path)- .unwrap_or_else(|e| panic!("Failed to create lock file at {:?}: {}", lock_path, e));-- // Acquire exclusive lock (blocks if another process is building)- lock_file.lock_exclusive().unwrap_or_else(|e| {- panic!(- "Failed to acquire exclusive lock on {:?}: {}. \- This may indicate a deadlock or filesystem permission issue.",- lock_path, e- )- });-- // While holding lock: build if binary doesn't exist- if !bin_path.exists() {- let status = Command::new("cargo")- .args(["build", "-p", "dev-detach", "--quiet"])- .status()- .unwrap();-- if !status.success() {- panic!("Failed to build dev-detach binary");- }- }-- // Release lock before returning- drop(lock_file);-- bin_path-}+/// Path to dev-detach binary (built automatically as part of the crate).+const DEV_DETACH_BIN: &str = env!("CARGO_BIN_EXE_dev-detach");/// Convert signal number to human-readable name#[cfg(unix)]@@ -81,10 +32,8 @@ pub fn get_shell_binary(shell: &str) -> &str {}/// Build a command to execute a shell script via dev-detach.-/// Uses pre-built binary to avoid cargo lock contention during concurrent test execution.fn build_shell_command(repo: &TestRepo, shell: &str, script: &str) -> Command {- // Use pre-built dev-detach binary (no cargo invocation)- let mut cmd = Command::new(get_dev_detach_bin());+ let mut cmd = Command::new(DEV_DETACH_BIN);repo.clean_cli_env(&mut cmd);// Prevent user shell config from leaking into testsdiff --git a/tests/helpers/dev-detach/Cargo.toml b/tests/helpers/dev-detach/Cargo.tomldeleted file mode 100644index 292f40863..000000000--- a/tests/helpers/dev-detach/Cargo.toml+++ /dev/null@@ -1,17 +0,0 @@-# Test helper binary for TTY isolation in shell integration tests.-# This is a workspace member (not a separate workspace) to share target/ and Cargo.lock.-# Never published to crates.io (publish = false) - only used during development and CI.-[package]-name = "dev-detach"-version = "0.1.0"-edition = "2024"-publish = false--[dependencies]-# Only needed on Unix for setsid() functionality-[target.'cfg(unix)'.dependencies]-nix = { version = "0.30", default-features = false, features = ["process", "signal"] }--[lints.rust]-# dev-detach uses nix crate's safe wrappers, no direct unsafe code-unsafe_code = "forbid"diff --git a/tests/helpers/dev-detach/src/main.rs b/tests/helpers/dev-detach/src/main.rsdeleted file mode 100644index 0d135c682..000000000--- a/tests/helpers/dev-detach/src/main.rs+++ /dev/null@@ -1,58 +0,0 @@-//! Dev-only helper binary for TTY isolation in tests.-//!-//! This binary detaches child processes from controlling terminals by calling setsid()-//! before exec'ing the target command. This prevents PTY-related hangs when running-//! nextest in environments like unbuffer or script.-//!-//! Usage: dev-detach \<command\> [args...]-//!-//! The binary becomes a new session leader with no controlling terminal, then replaces-//! itself with the target command via execvp().-//!-//! Note: This binary is Unix-only. On Windows, it builds as a stub that exits with an error.--#[cfg(unix)]-use nix::unistd::{execvp, setsid};-#[cfg(unix)]-use std::ffi::CString;-use std::{env, process};--fn main() {- #[cfg(unix)]- {- // Become a new session leader with no controlling terminal.- // This is the key to preventing PTY-related hangs - the child process- // starts life completely detached from any terminal.- if let Err(e) = setsid() {- eprintln!("dev-detach: setsid failed: {}", e);- process::exit(1);- }-- // Get command and arguments from our argv- let args: Vec<String> = env::args().skip(1).collect();- if args.is_empty() {- eprintln!("usage: dev-detach <command> [args...]");- process::exit(2);- }-- // Convert to CStrings for execvp- let prog = CString::new(args[0].clone()).unwrap();- let cargs: Vec<CString> = args- .iter()- .map(|a| CString::new(a.as_str()).unwrap())- .collect();-- // Replace this process with the target command.- // If execvp returns, it failed.- let _ = execvp(prog.as_c_str(), &cargs);- eprintln!("dev-detach: execvp failed");- process::exit(127);- }-- #[cfg(not(unix))]- {- eprintln!("dev-detach is only supported on Unix systems");- eprintln!("This binary is used for TTY isolation in tests and is not needed on Windows");- process::exit(1);- }-}diff --git a/tests/helpers/dev-detach/src/setup-select-test.rs b/tests/helpers/dev-detach/src/setup-select-test.rsdeleted file mode 100644index 77a495494..000000000--- a/tests/helpers/dev-detach/src/setup-select-test.rs+++ /dev/null@@ -1,182 +0,0 @@-//! Helper binary to setup a test environment for debugging `wt beta select`-//!-//! This creates a temporary git repository with a known state:-//! - main branch with 3 commits-//! - feature branch with 15 commits ahead of main (100 lines per file)-//! - Multiple worktrees with varying amounts of work-//! - Some uncommitted changes in the feature worktree-//!-//! Run with: cargo run --bin setup-select-test-//! Then cd into the printed path and run: wt beta select--use std::fs;-use std::io::{self, Write};-use std::path::PathBuf;-use std::process::Command;--fn main() {- println!("Setting up test environment for `wt beta select`...\n");-- // Create temp directory in /tmp- let temp_base = std::env::temp_dir().join("wt-select-test");- if temp_base.exists() {- fs::remove_dir_all(&temp_base).unwrap();- }- fs::create_dir(&temp_base).unwrap();-- let root = temp_base.join("test-repo");- fs::create_dir(&root).unwrap();- let root = root.canonicalize().unwrap();-- // Initialize git repo- git(&root, &["init", "-b", "main"]);- git(&root, &["config", "user.name", "Test User"]);- git(&root, &["config", "user.email", "[email protected]"]);-- // Create commits on main- for i in 1..=3 {- fs::write(- root.join(format!("file{}.txt", i)),- format!("content {}", i),- )- .unwrap();- git(&root, &["add", "."]);- git(&root, &["commit", "-m", &format!("Main commit {}", i)]);- }-- // Create feature branch with commits ahead - MORE COMMITS AND BIGGER FILES- git(&root, &["switch", "-c", "feature"]);- for i in 1..=15 {- // Create larger files with more content- let mut content = String::new();- for line in 1..=100 {- content.push_str(&format!("Line {} of feature file {}\n", line, i));- }- fs::write(root.join(format!("feature{}.txt", i)), content).unwrap();- git(&root, &["add", "."]);- git(- &root,- &[- "commit",- "-m",- &format!("Feature commit {}: Add feature{}.txt with 100 lines", i, i),- ],- );- }-- // Switch back to main in primary worktree BEFORE creating worktrees- git(&root, &["switch", "main"]);-- // Create multiple worktrees to simulate realistic scenario-- // Feature worktree (15 commits ahead)- let feature_wt = temp_base.join("feature-wt");- git(- &root,- &["worktree", "add", feature_wt.to_str().unwrap(), "feature"],- );-- // Create more branches with different amounts of work- for (i, num_commits) in [(2, 5), (3, 3), (4, 8), (5, 2)].iter() {- let branch_name = format!("branch{}", i);- git(&root, &["branch", &branch_name, "main"]);-- let wt_path = temp_base.join(format!("branch{}-wt", i));- git(- &root,- &["worktree", "add", wt_path.to_str().unwrap(), &branch_name],- );-- // Add commits to this branch via its worktree- for j in 1..=*num_commits {- let file_content = format!("Content for {} commit {}\n", branch_name, j);- fs::write(wt_path.join(format!("file{}.txt", j)), file_content).unwrap();- let mut cmd = Command::new("git");- git_env(&mut cmd);- cmd.args(["add", "."])- .current_dir(&wt_path)- .output()- .unwrap();-- let mut cmd = Command::new("git");- git_env(&mut cmd);- cmd.args(["commit", "-m", &format!("{} commit {}", branch_name, j)])- .current_dir(&wt_path)- .output()- .unwrap();- }- }-- // Add uncommitted changes to feature worktree- let feature_wt = feature_wt.canonicalize().unwrap();- fs::write(feature_wt.join("uncommitted.txt"), "uncommitted changes").unwrap();-- // Create some branches without worktrees- git(&root, &["branch", "no-worktree-1", "main"]);- git(&root, &["branch", "no-worktree-2", "main"]);-- println!("✅ Test environment ready!\n");- println!("Repository path: {}", root.display());- println!();- println!("Worktrees created:");- println!(" - main (primary): {}", root.display());- println!(" - feature: 15 commits ahead, 1 uncommitted file");- println!(" - branch2: 5 commits ahead");- println!(" - branch3: 3 commits ahead");- println!(" - branch4: 8 commits ahead");- println!(" - branch5: 2 commits ahead");- println!();- println!("Branches without worktrees:");- println!(" - no-worktree-1, no-worktree-2");- println!();- println!("Total: 6 worktrees + 2 branches = 8 items in list");- println!();- println!("To test:");- println!();- println!("Method 1 - Using cd:");- println!(" cd {}", root.display());- println!(" cargo run --quiet -- beta select");- println!();- println!("Method 2 - Using -C flag:");- println!(" cargo run --quiet -- -C {} beta select", root.display());- println!();- println!("Expected behavior:");- println!(" - Navigate with arrow keys through 8 items");- println!(" - Press 3 on 'feature': Shows LARGE diff (15 files, 1500 lines)");- println!(" - Press 3 on other branches: Shows smaller diffs");- println!();- println!("Press Enter to clean up and exit (or Ctrl+C to leave the test repo)...");-- io::stdout().flush().unwrap();- let mut input = String::new();- io::stdin().read_line(&mut input).unwrap();-- println!("Cleaning up...");- if let Err(e) = fs::remove_dir_all(&temp_base) {- eprintln!("Warning: Failed to clean up test directory: {}", e);- eprintln!("You may need to manually remove: {}", temp_base.display());- } else {- println!("Test environment cleaned up.");- }-}--fn git_env(cmd: &mut Command) {- // Set git config for test environment- cmd.env("GIT_CONFIG_GLOBAL", "/dev/null");- cmd.env("GIT_CONFIG_SYSTEM", "/dev/null");- cmd.env("GIT_AUTHOR_DATE", "2025-01-01T00:00:00Z");- cmd.env("GIT_COMMITTER_DATE", "2025-01-01T00:00:00Z");-}--fn git(repo: &PathBuf, args: &[&str]) {- let mut cmd = Command::new("git");- git_env(&mut cmd);- let output = cmd.args(args).current_dir(repo).output().unwrap();-- if !output.status.success() {- eprintln!("Git command failed: git {}", args.join(" "));- eprintln!("stdout: {}", String::from_utf8_lossy(&output.stdout));- eprintln!("stderr: {}", String::from_utf8_lossy(&output.stderr));- std::process::exit(1);- }-}diff --git a/tests/integration_tests/e2e_shell.rs b/tests/integration_tests/e2e_shell.rsindex 189acbdf3..0789b63e7 100644--- a/tests/integration_tests/e2e_shell.rs+++ b/tests/integration_tests/e2e_shell.rs@@ -1,3 +1,6 @@+//! End-to-end shell integration tests.+#![cfg(feature = "shell-integration-tests")]+use crate::common::{TestRepo,shell::{execute_shell_script, generate_init_code, path_export_syntax, wt_bin_dir},diff --git a/tests/integration_tests/e2e_shell_post_start.rs b/tests/integration_tests/e2e_shell_post_start.rsindex 4bb7e4e20..dd8e44631 100644--- a/tests/integration_tests/e2e_shell_post_start.rs+++ b/tests/integration_tests/e2e_shell_post_start.rs@@ -1,3 +1,6 @@+//! Post-start command shell integration tests.+#![cfg(feature = "shell-integration-tests")]+use crate::common::{TestRepo, resolve_git_common_dir,shell::{execute_shell_script, generate_init_code, path_export_syntax, wt_bin_dir},diff --git a/tests/integration_tests/readme_sync.rs b/tests/integration_tests/readme_sync.rsindex 1ecd9c6d3..36996114e 100644--- a/tests/integration_tests/readme_sync.rs+++ b/tests/integration_tests/readme_sync.rs@@ -173,9 +173,8 @@ fn get_help_output(command: &str, project_root: &Path) -> Result<String, String>return Err(format!("Command must end with '--help-md': {}", command));}- // Build the cargo run command- let output = Command::new("cargo")- .args(["run", "-q", "--"])+ // Use the already-built binary from cargo test+ let output = Command::new(env!("CARGO_BIN_EXE_wt")).args(&args[1..]) // Skip "wt" prefix.current_dir(project_root).output()