Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Add Cmd builder for cleaner command execution with stdin support (#572)
Maximilian Roos4db6d82f7892
diff --git a/.claude/rules/output-system-architecture.md b/.claude/rules/output-system-architecture.mdindex 0d2be2dee..1b66c61c9 100644--- a/.claude/rules/output-system-architecture.md+++ b/.claude/rules/output-system-architecture.md@@ -69,7 +69,7 @@ Examples:## Security`WORKTRUNK_DIRECTIVE_FILE` is automatically removed from spawned subprocesses-(via `shell_exec::run()`). This prevents hooks from writing to the directive+(via `shell_exec::Cmd`). This prevents hooks from writing to the directivefile.## Windows Compatibility (Git Bash / MSYS2)diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yamlindex c751895de..fdebda33c 100644--- a/.pre-commit-config.yaml+++ b/.pre-commit-config.yaml@@ -66,11 +66,11 @@ repos:files: '^tests/'- id: no-direct-cmd-outputname: no-direct-cmd-output- description: Use shell_exec::run() instead of cmd.output() for consistent logging+ description: Use shell_exec::Cmd instead of cmd.output() for consistent logginglanguage: pygreptypes: ["rust"]entry: '\.output\(\)'- # shell_exec.rs: defines run() which legitimately calls .output()+ # shell_exec.rs: defines Cmd which legitimately calls .output()# select.rs: skim API's selected.output() is not Command::output()# tests/benches: test utilities run commands directlyexclude: '^(src/shell_exec\.rs|src/commands/select\.rs|tests/|benches/)'diff --git a/CLAUDE.md b/CLAUDE.mdindex 708f044da..065389660 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -122,22 +122,35 @@ Never risk data loss without explicit user consent. A failed command that preser## Command Execution Principles-### All Commands Through `shell_exec::run`+### All Commands Through `shell_exec::Cmd`-All external commands go through `shell_exec::run()` for consistent logging and tracing:+All external commands go through `shell_exec::Cmd` for consistent logging and tracing:```rust-use crate::shell_exec::run;+use crate::shell_exec::Cmd;-let mut cmd = Command::new("git");-cmd.args(["status", "--porcelain"]);-let output = run(&mut cmd, Some("worktree-name"))?; // context for git commands-let output = run(&mut cmd, None)?; // None for standalone tools+let output = Cmd::new("git")+ .args(["status", "--porcelain"])+ .current_dir(&worktree_path)+ .context("worktree-name") // for git commands+ .run()?;++let output = Cmd::new("gh")+ .args(["pr", "list"])+ .run()?; // no context for standalone tools```-Never use `cmd.output()` directly. `run()` provides debug logging (`$ git status [worktree-name]`) and timing traces (`[wt-trace] cmd="..." dur=12.3ms ok=true`).+Never use `cmd.output()` directly. `Cmd` provides debug logging (`$ git status [worktree-name]`) and timing traces (`[wt-trace] cmd="..." dur=12.3ms ok=true`).++For git commands, prefer `Repository::run_command()` which wraps `Cmd` with worktree context.-For git commands, prefer `Repository::run_command()` which wraps `shell_exec::run` with worktree context.+For commands that need stdin piping:+```rust+let output = Cmd::new("git")+ .args(["diff-tree", "--stdin", "--numstat"])+ .stdin(hashes.join("\n"))+ .run()?;+```### Real-time Output Streamingdiff --git a/src/commands/config.rs b/src/commands/config.rsindex cf2c47154..8d80f1071 100644--- a/src/commands/config.rs+++ b/src/commands/config.rs@@ -157,14 +157,11 @@ pub fn handle_config_show(full: bool) -> anyhow::Result<()> {/// Check if Claude Code CLI is availablefn is_claude_available() -> bool {- use std::process::{Command, Stdio};- use worktrunk::shell_exec::run;+ use worktrunk::shell_exec::Cmd;- let mut cmd = Command::new("claude");- cmd.args(["--version"]);- cmd.stdin(Stdio::null());-- run(&mut cmd, None)+ Cmd::new("claude")+ .arg("--version")+ .run().map(|o| o.status.success()).unwrap_or(false)}@@ -193,13 +190,9 @@ fn is_plugin_installed() -> bool {/// Get the git version string (e.g., "2.47.1")fn get_git_version() -> Option<String> {- use std::process::Command;- use worktrunk::shell_exec::run;-- let mut cmd = Command::new("git");- cmd.args(["--version"]);+ use worktrunk::shell_exec::Cmd;- let output = run(&mut cmd, None).ok()?;+ let output = Cmd::new("git").arg("--version").run().ok()?;if !output.status.success() {return None;}@@ -796,8 +789,7 @@ fn render_ci_tool_status(/// Returns true if compinit is NOT enabled (i.e., user needs to add it)./// Returns false if compinit is enabled or we can't determine (fail-safe: don't warn).fn check_zsh_compinit_missing() -> bool {- use std::process::Command;- use worktrunk::shell_exec::run;+ use worktrunk::shell_exec::Cmd;// Allow tests to bypass this check since zsh subprocess behavior varies across CI envsif std::env::var("WORKTRUNK_TEST_COMPINIT_CONFIGURED").is_ok() {@@ -814,12 +806,13 @@ fn check_zsh_compinit_missing() -> bool {// This ensures we're checking the USER's configuration, not system defaults// Suppress stderr to avoid noise like "can't change option: zle"// The (( ... )) arithmetic returns exit 0 if true (compdef exists), 1 if false- let mut cmd = Command::new("zsh");- cmd.args(["--no-globalrcs", "-ic", "(( $+functions[compdef] ))"]);// Suppress zsh's "insecure directories" warning from compinit.// See detailed rationale in shell::detect_zsh_compinit().- cmd.env("ZSH_DISABLE_COMPFIX", "true");- let Ok(output) = run(&mut cmd, None) else {+ let Ok(output) = Cmd::new("zsh")+ .args(["--no-globalrcs", "-ic", "(( $+functions[compdef] ))"])+ .env("ZSH_DISABLE_COMPFIX", "true")+ .run()+ else {return false; // Can't determine, don't warn};diff --git a/src/commands/list/ci_status.rs b/src/commands/list/ci_status.rsindex b06719448..3a74e9cc2 100644--- a/src/commands/list/ci_status.rs+++ b/src/commands/list/ci_status.rs@@ -1,10 +1,9 @@use serde::{Deserialize, Serialize, de::DeserializeOwned};use std::fs;use std::path::{Path, PathBuf};-use std::process::Command;use worktrunk::git::{Repository, parse_owner_repo, parse_remote_owner};use worktrunk::path::sanitize_for_filename;-use worktrunk::shell_exec::run;+use worktrunk::shell_exec::Cmd;use worktrunk::utils::get_now;/// CI platform detected from project config override or remote URL.@@ -677,14 +676,13 @@ fn get_gitlab_project_id(repo: &Repository) -> Option<u64> {let repo_root = repo.current_worktree().root().ok()?;// Use glab repo view to get the project info as JSON- let mut cmd = Command::new("glab");- cmd.args(["repo", "view", "--output", "json"]);- cmd.current_dir(&repo_root);// Disable color/pager to avoid ANSI noise in JSON output- configure_non_interactive(&mut cmd);- cmd.env("PAGER", "cat");-- let output = run(&mut cmd, None).ok()?;+ let output = non_interactive_cmd("glab")+ .args(["repo", "view", "--output", "json"])+ .current_dir(&repo_root)+ .env("PAGER", "cat")+ .run()+ .ok()?;if !output.status.success() {return None;@@ -701,40 +699,29 @@ fn get_gitlab_project_id(repo: &Repository) -> Option<u64> {.map(|info| info.id)}-/// Configure command for non-interactive batch execution.+/// Create a Cmd configured for non-interactive batch execution.////// This prevents tools like `gh` and `glab` from:-/// - Prompting for user input (stdin set to /dev/null)+/// - Prompting for user input/// - Using TTY-specific output formatting/// - Opening browsers for authentication-fn configure_non_interactive(cmd: &mut Command) {- use std::process::Stdio;- cmd.stdin(Stdio::null());- cmd.env_remove("CLICOLOR_FORCE");- cmd.env_remove("GH_FORCE_TTY");- cmd.env("NO_COLOR", "1");- cmd.env("CLICOLOR", "0");- cmd.env("GH_PROMPT_DISABLED", "1");+fn non_interactive_cmd(program: &str) -> Cmd {+ Cmd::new(program)+ .env_remove("CLICOLOR_FORCE")+ .env_remove("GH_FORCE_TTY")+ .env("NO_COLOR", "1")+ .env("CLICOLOR", "0")+ .env("GH_PROMPT_DISABLED", "1")}/// Check if a CLI tool is available///-/// On Windows, CreateProcessW (via Command::new) searches PATH for .exe files.+/// On Windows, CreateProcessW (via Cmd) searches PATH for .exe files./// We provide .exe mocks in tests via mock-stub, so this works consistently.-///-/// Uses `Stdio::null()` for stdin to prevent tools like `gh` from prompting-/// for user input when they detect a TTY.fn tool_available(tool: &str, args: &[&str]) -> bool {- use std::process::Stdio;-- // Use Command::new(tool) directly on all platforms.- // On Windows, CreateProcessW searches PATH for .exe files.- // This is simpler and more reliable than going through cmd.exe.- let mut cmd = Command::new(tool);- cmd.args(args);- cmd.stdin(Stdio::null());-- run(&mut cmd, None)+ Cmd::new(tool)+ .args(args.iter().copied())+ .run().map(|o| o.status.success()).unwrap_or(false)}@@ -1244,24 +1231,22 @@ impl PrStatus {//// We fetch up to MAX_PRS_TO_FETCH PRs to handle branch name collisions, then filter// client-side by headRepositoryOwner to find PRs from our fork.- let mut cmd = Command::new("gh");- cmd.args([- "pr",- "list",- "--head",- branch,- "--state",- "open",- "--limit",- &MAX_PRS_TO_FETCH.to_string(),- "--json",- "headRefOid,mergeStateStatus,statusCheckRollup,url,headRepositoryOwner",- ]);-- configure_non_interactive(&mut cmd);- cmd.current_dir(&repo_root);-- let output = match run(&mut cmd, None) {+ let output = match non_interactive_cmd("gh")+ .args([+ "pr",+ "list",+ "--head",+ branch,+ "--state",+ "open",+ "--limit",+ &MAX_PRS_TO_FETCH.to_string(),+ "--json",+ "headRefOid,mergeStateStatus,statusCheckRollup,url,headRepositoryOwner",+ ])+ .current_dir(&repo_root)+ .run()+ {Ok(output) => output,Err(e) => {log::warn!("gh pr list failed to execute for branch {}: {}", branch, e);@@ -1357,20 +1342,20 @@ impl PrStatus {// Fetch MRs with matching source branch.// We filter client-side by source_project_id (numeric project ID comparison).- let mut cmd = Command::new("glab");- cmd.args([- "mr",- "list",- "--source-branch",- branch,- "--state=opened",- &format!("--per-page={}", MAX_PRS_TO_FETCH),- "--output",- "json",- ]);- cmd.current_dir(&repo_root);-- let output = match run(&mut cmd, None) {+ let output = match Cmd::new("glab")+ .args([+ "mr",+ "list",+ "--source-branch",+ branch,+ "--state=opened",+ &format!("--per-page={}", MAX_PRS_TO_FETCH),+ "--output",+ "json",+ ])+ .current_dir(&repo_root)+ .run()+ {Ok(output) => output,Err(e) => {log::warn!(@@ -1452,18 +1437,16 @@ impl PrStatus {let (owner, repo_name) = get_owner_repo(repo)?;// Use GitHub's check-runs API to get all checks for this commit- let mut cmd = Command::new("gh");- cmd.args([- "api",- &format!("repos/{owner}/{repo_name}/commits/{local_head}/check-runs"),- "--jq",- ".check_runs | map({status, conclusion})",- ]);-- configure_non_interactive(&mut cmd);- cmd.current_dir(&repo_root);-- let output = match run(&mut cmd, None) {+ let output = match non_interactive_cmd("gh")+ .args([+ "api",+ &format!("repos/{owner}/{repo_name}/commits/{local_head}/check-runs"),+ "--jq",+ ".check_runs | map({status, conclusion})",+ ])+ .current_dir(&repo_root)+ .run()+ {Ok(output) => output,Err(e) => {log::warn!(@@ -1506,13 +1489,11 @@ impl PrStatus {}// Get most recent pipeline for the branch using JSON output- use std::process::Stdio;- let mut cmd = Command::new("glab");- cmd.args(["ci", "list", "--per-page", "1", "--output", "json"])+ let output = match Cmd::new("glab")+ .args(["ci", "list", "--per-page", "1", "--output", "json"]).env("BRANCH", branch) // glab ci list uses BRANCH env var- .stdin(Stdio::null());-- let output = match run(&mut cmd, None) {+ .run()+ {Ok(output) => output,Err(e) => {log::warn!(diff --git a/src/commands/select.rs b/src/commands/select.rsindex 233d3637c..47023d627 100644--- a/src/commands/select.rs+++ b/src/commands/select.rs@@ -11,6 +11,7 @@ use std::time::{Duration, Instant};use worktrunk::config::WorktrunkConfig;use worktrunk::git::{Repository, parse_numstat_line};use worktrunk::shell::extract_filename_from_path;+use worktrunk::shell_exec::Cmd;use super::list::collect;use super::list::layout::{DiffDisplayConfig, DiffVariant};@@ -706,35 +707,21 @@ impl WorktreeSkimItem {/// Batch fetch diffstats for multiple commits using git diff-tree --stdin./// Returns a map of full_hash -> (insertions, deletions).///-/// Note: This bypasses shell_exec::run() because it requires stdin piping,-/// which run() doesn't support. Failures are silent (preview context).+/// Failures are silent (preview context).fn batch_fetch_stats(repo: &Repository, hashes: &[String]) -> HashMap<String, (usize, usize)> {- use std::io::Write;-if hashes.is_empty() {return HashMap::new();}- let mut cmd = Command::new("git");// --root: include stats for root commits (no parent to diff against)- cmd.args(["diff-tree", "--numstat", "-r", "--root", "--stdin"])+ // Each hash needs a trailing newline for git to process it+ let stdin_data = hashes.iter().map(|h| format!("{h}\n")).collect::<String>();+ let Ok(output) = Cmd::new("git")+ .args(["diff-tree", "--numstat", "-r", "--root", "--stdin"]).current_dir(repo.worktree_base().unwrap_or_else(|_| ".".into()))- .stdin(Stdio::piped())- .stdout(Stdio::piped())- .stderr(Stdio::null());-- let Ok(mut child) = cmd.spawn() else {- return HashMap::new();- };-- // Write hashes to stdin- if let Some(mut stdin) = child.stdin.take() {- for hash in hashes {- let _ = writeln!(stdin, "{}", hash);- }- }-- let Ok(output) = child.wait_with_output() else {+ .stdin(stdin_data)+ .run()+ else {return HashMap::new();};diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rsindex 7419119cb..62c925147 100644--- a/src/commands/step_commands.rs+++ b/src/commands/step_commands.rs@@ -564,20 +564,20 @@ fn list_ignored_entries(worktree_path: &Path,context: &str,) -> anyhow::Result<Vec<(std::path::PathBuf, bool)>> {- use std::process::Command;- use worktrunk::shell_exec;-- let mut cmd = Command::new("git");- cmd.args([- "ls-files",- "--ignored",- "--exclude-standard",- "-o",- "--directory",- ])- .current_dir(worktree_path);-- let output = shell_exec::run(&mut cmd, Some(context)).context("Failed to run git ls-files")?;+ use worktrunk::shell_exec::Cmd;++ let output = Cmd::new("git")+ .args([+ "ls-files",+ "--ignored",+ "--exclude-standard",+ "-o",+ "--directory",+ ])+ .current_dir(worktree_path)+ .context(context)+ .run()+ .context("Failed to run git ls-files")?;if !output.status.success() {let stderr = String::from_utf8_lossy(&output.stderr);diff --git a/src/diagnostic.rs b/src/diagnostic.rsindex b826c973a..f65d465b2 100644--- a/src/diagnostic.rs+++ b/src/diagnostic.rs@@ -43,13 +43,12 @@//! ```//!use std::path::PathBuf;-use std::process::{Command, Stdio};use anyhow::Context;use color_print::cformat;use minijinja::{Environment, context};use worktrunk::git::Repository;-use worktrunk::shell_exec::run;+use worktrunk::shell_exec::Cmd;use crate::cli::version_str;use crate::output;@@ -231,11 +230,11 @@ fn truncate_log(content: &str) -> String {/// Get git version string.fn get_git_version() -> anyhow::Result<String> {- let mut cmd = Command::new("git");- cmd.args(["--version"]);- cmd.stdin(Stdio::null());+ let output = Cmd::new("git")+ .arg("--version")+ .run()+ .context("Failed to run git --version")?;- let output = run(&mut cmd, None).context("Failed to run git --version")?;let stdout = String::from_utf8_lossy(&output.stdout);let version = stdout.trim()diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex c06b35aa9..b122ceecd 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -14,8 +14,8 @@//! - `config.rs` - Git config, hints, markers, and default branch detection//! - `integration.rs` - Integration detection (same commit, ancestor, trees match)+use crate::shell_exec::Cmd;use std::path::{Path, PathBuf};-use std::process::Command;use std::sync::{Arc, OnceLock};use dashmap::DashMap;@@ -214,13 +214,11 @@ impl Repository {/// Resolve the git common directory for a path.fn resolve_git_common_dir(discovery_path: &Path) -> anyhow::Result<PathBuf> {- use crate::shell_exec::run;-- let mut cmd = Command::new("git");- cmd.args(["rev-parse", "--git-common-dir"]);- cmd.current_dir(discovery_path);-- let output = run(&mut cmd, Some(&path_to_logging_context(discovery_path)))+ let output = Cmd::new("git")+ .args(["rev-parse", "--git-common-dir"])+ .current_dir(discovery_path)+ .context(path_to_logging_context(discovery_path))+ .run().context("Failed to execute: git rev-parse --git-common-dir")?;if !output.status.success() {@@ -455,13 +453,11 @@ impl Repository {/// # Ok::<(), anyhow::Error>(())/// ```pub fn run_command(&self, args: &[&str]) -> anyhow::Result<String> {- use crate::shell_exec::run;-- let mut cmd = Command::new("git");- cmd.args(args);- cmd.current_dir(&self.discovery_path);-- let output = run(&mut cmd, Some(&self.logging_context()))+ let output = Cmd::new("git")+ .args(args.iter().copied())+ .current_dir(&self.discovery_path)+ .context(self.logging_context())+ .run().with_context(|| format!("Failed to execute: git {}", args.join(" ")))?;if !output.status.success() {@@ -515,13 +511,11 @@ impl Repository {/// Use this when exit codes have semantic meaning beyond success/failure./// For most cases, prefer `run_command` (returns stdout) or `run_command_check` (returns bool).pub(super) fn run_command_output(&self, args: &[&str]) -> anyhow::Result<std::process::Output> {- use crate::shell_exec::run;-- let mut cmd = Command::new("git");- cmd.args(args);- cmd.current_dir(&self.discovery_path);-- run(&mut cmd, Some(&self.logging_context()))+ Cmd::new("git")+ .args(args.iter().copied())+ .current_dir(&self.discovery_path)+ .context(self.logging_context())+ .run().with_context(|| format!("Failed to execute: git {}", args.join(" ")))}}diff --git a/src/git/repository/working_tree.rs b/src/git/repository/working_tree.rsindex 7d28a0259..b3922983d 100644--- a/src/git/repository/working_tree.rs+++ b/src/git/repository/working_tree.rs@@ -1,9 +1,10 @@//! WorkingTree - a borrowed handle for worktree-specific git operations.use std::path::{Path, PathBuf};-use std::process::Command;use anyhow::{Context, bail};++use crate::shell_exec::Cmd;use dunce::canonicalize;use super::{GitError, LineDiff, Repository};@@ -53,13 +54,11 @@ pub struct WorkingTree<'a> {impl<'a> WorkingTree<'a> {/// Run a git command in this worktree and return stdout.pub fn run_command(&self, args: &[&str]) -> anyhow::Result<String> {- use crate::shell_exec::run;-- let mut cmd = Command::new("git");- cmd.args(args);- cmd.current_dir(&self.path);-- let output = run(&mut cmd, Some(&path_to_logging_context(&self.path)))+ let output = Cmd::new("git")+ .args(args.iter().copied())+ .current_dir(&self.path)+ .context(path_to_logging_context(&self.path))+ .run().with_context(|| format!("Failed to execute: git {}", args.join(" ")))?;if !output.status.success() {diff --git a/src/llm.rs b/src/llm.rsindex a907c3bcf..2827f9b7e 100644--- a/src/llm.rs+++ b/src/llm.rs@@ -1,11 +1,10 @@use anyhow::Context;-use std::io::Write;use std::path::{Path, PathBuf};-use std::process::{self, Stdio};use std::sync::atomic::{AtomicBool, Ordering};use worktrunk::config::CommitGenerationConfig;use worktrunk::git::Repository;use worktrunk::path::format_path_for_display;+use worktrunk::shell_exec::Cmd;use worktrunk::styling::warning_message;use minijinja::Environment;@@ -263,39 +262,17 @@ const DEFAULT_SQUASH_TEMPLATE: &str = r#"Combine these commits into a single com/// This is the canonical way to execute LLM commands in this codebase./// All LLM execution should go through this function to maintain consistency.fn execute_llm_command(command: &str, args: &[String], prompt: &str) -> anyhow::Result<String> {- // Build command args- let mut cmd = process::Command::new(command);- cmd.args(args);-- cmd.stdin(Stdio::piped())- .stdout(Stdio::piped())- .stderr(Stdio::piped())- // Prevent subprocesses from writing to the directive file- .env_remove(worktrunk::shell_exec::DIRECTIVE_FILE_ENV_VAR);-- // Log execution- log::debug!("$ {} {}", command, args.join(" "));+ // Log prompt for debugging (Cmd logs the command itself)log::debug!(" Prompt (stdin):");for line in prompt.lines() {log::debug!(" {}", line);}- let mut child = cmd.spawn().context("Failed to spawn LLM command")?;-- // Write prompt to stdin- // Note: We ignore BrokenPipe errors because some commands (like `echo`) exit- // immediately without reading stdin. This is fine as long as they produce output.- if let Some(mut stdin) = child.stdin.take()- && let Err(e) = stdin.write_all(prompt.as_bytes())- && e.kind() != std::io::ErrorKind::BrokenPipe- {- return Err(e).context("Failed to write prompt to LLM stdin");- }- // stdin is dropped here, closing the pipe-- let output = child- .wait_with_output()- .context("Failed to wait for LLM output")?;+ let output = Cmd::new(command)+ .args(args.iter().map(String::as_str))+ .stdin(prompt)+ .run()+ .context("Failed to spawn LLM command")?;if !output.status.success() {let stderr = String::from_utf8_lossy(&output.stderr);diff --git a/src/main.rs b/src/main.rsindex 7b7fb98ad..125b0d53a 100644--- a/src/main.rs+++ b/src/main.rs@@ -1808,14 +1808,11 @@ fn write_vv_diagnostic(verbose: u8, command_line: &str, error_msg: Option<&str>)/// Check if the GitHub CLI (gh) is installed.fn is_gh_installed() -> bool {- use std::process::{Command, Stdio};- use worktrunk::shell_exec::run;+ use worktrunk::shell_exec::Cmd;- let mut cmd = Command::new("gh");- cmd.args(["--version"]);- cmd.stdin(Stdio::null());-- run(&mut cmd, None)+ Cmd::new("gh")+ .arg("--version")+ .run().map(|o| o.status.success()).unwrap_or(false)}diff --git a/src/path.rs b/src/path.rsindex 2b3210eb9..3ccea00db 100644--- a/src/path.rs+++ b/src/path.rs@@ -1,9 +1,7 @@use std::path::{Path, PathBuf};#[cfg(windows)]-use crate::shell_exec::run;-#[cfg(windows)]-use std::process::Command;+use crate::shell_exec::Cmd;/// Convert a path to POSIX format for Git Bash compatibility.///@@ -28,9 +26,7 @@ pub fn to_posix_path(path: &str) -> String {return path.to_string();};- let mut cmd = Command::new(&cygpath);- cmd.arg("-u").arg(path);- let Ok(output) = run(&mut cmd, None) else {+ let Ok(output) = Cmd::new(cygpath.to_string_lossy()).args(["-u", path]).run() else {return path.to_string();};diff --git a/src/shell_exec.rs b/src/shell_exec.rsindex 66cc53b27..a2b4bb92f 100644--- a/src/shell_exec.rs+++ b/src/shell_exec.rs@@ -220,30 +220,6 @@ pub fn trace_instant(event: &str) {log::debug!("[wt-trace] ts={} tid={} event=\"{}\"", ts, tid, event);}-/// Execute a command with timing and debug logging.-///-/// This is the **only** way to run external commands in worktrunk. All command execution-/// must go through this function to ensure consistent logging and tracing.-///-/// If a thread-local timeout is set via `set_command_timeout()`, the command will be-/// killed if it exceeds that duration.-///-/// The `WORKTRUNK_DIRECTIVE_FILE` environment variable is automatically removed from spawned-/// processes to prevent hooks from discovering and writing to the directive file.-///-/// ```text-/// $ git status [worktree-name] # with context-/// $ gh pr list # without context-/// [wt-trace] context=worktree cmd="..." dur=12.3ms ok=true-/// ```-///-/// The `context` parameter is typically the worktree name for git commands, or `None` for-/// standalone CLI tools like `gh` and `glab`.-pub fn run(cmd: &mut Command, context: Option<&str>) -> std::io::Result<std::process::Output> {- let timeout = COMMAND_TIMEOUT.with(|t| t.get());- run_with_timeout(cmd, context, timeout)-}-/// Extract numeric thread ID from ThreadId's debug format./// ThreadId debug format is "ThreadId(N)" where N is the numeric ID.fn thread_id_number() -> u64 {@@ -256,106 +232,6 @@ fn thread_id_number() -> u64 {.unwrap_or(0)}-/// Execute a command with an optional timeout.-///-/// Like `run()`, but allows specifying a timeout. If the command doesn't complete within-/// the timeout, it is killed and an error is returned.-///-/// Returns `std::io::ErrorKind::TimedOut` if the command times out.-pub fn run_with_timeout(- cmd: &mut Command,- context: Option<&str>,- timeout: Option<std::time::Duration>,-) -> std::io::Result<std::process::Output> {- use std::time::Instant;-- // Remove WORKTRUNK_DIRECTIVE_FILE to prevent hooks from writing to it- cmd.env_remove(DIRECTIVE_FILE_ENV_VAR);-- // Build command string for logging- let program = cmd.get_program().to_string_lossy();- let args: Vec<_> = cmd.get_args().map(|a| a.to_string_lossy()).collect();- let cmd_str = if args.is_empty() {- program.to_string()- } else {- format!("{} {}", program, args.join(" "))- };-- // Log command with optional context- match context {- Some(ctx) => log::debug!("$ {} [{}]", cmd_str, ctx),- None => log::debug!("$ {}", cmd_str),- }-- // Acquire semaphore to limit concurrent commands (prevents resource exhaustion)- // RAII guard ensures release even on panic- let _guard = get_semaphore().acquire();-- // Capture monotonic timestamp and thread ID for Chrome Trace Format support.- // Using Instant instead of SystemTime ensures monotonic timestamps even if- // the system clock steps backward.- let t0 = Instant::now();- let ts = t0.duration_since(*trace_epoch()).as_micros() as u64;- let tid = thread_id_number();-- // Execute with or without timeout- let result = match timeout {- None => cmd.output(),- Some(timeout_duration) => run_with_timeout_impl(cmd, timeout_duration),- };-- // Use microseconds to avoid precision loss from millisecond rounding- let dur_us = t0.elapsed().as_micros() as u64;-- // Log trace with timing, timestamp, and thread ID for concurrency analysis- match (&result, context) {- (Ok(output), Some(ctx)) => {- log::debug!(- "[wt-trace] ts={} tid={} context={} cmd=\"{}\" dur_us={} ok={}",- ts,- tid,- ctx,- cmd_str,- dur_us,- output.status.success()- );- }- (Ok(output), None) => {- log::debug!(- "[wt-trace] ts={} tid={} cmd=\"{}\" dur_us={} ok={}",- ts,- tid,- cmd_str,- dur_us,- output.status.success()- );- }- (Err(e), Some(ctx)) => {- log::debug!(- "[wt-trace] ts={} tid={} context={} cmd=\"{}\" dur_us={} err=\"{}\"",- ts,- tid,- ctx,- cmd_str,- dur_us,- e- );- }- (Err(e), None) => {- log::debug!(- "[wt-trace] ts={} tid={} cmd=\"{}\" dur_us={} err=\"{}\"",- ts,- tid,- cmd_str,- dur_us,- e- );- }- }-- result-}-/// Implementation of timeout-based command execution.////// Spawns the process, captures stdout/stderr in background threads, and waits with timeout.@@ -435,6 +311,236 @@ fn run_with_timeout_impl(})}+// ============================================================================+// Builder-style command execution+// ============================================================================++/// Builder for executing commands with logging, tracing, and optional stdin.+///+/// Provides the same benefits as `run()` (logging, semaphore, tracing) with a+/// cleaner interface that supports stdin piping.+///+/// # Examples+///+/// Basic usage:+/// ```ignore+/// let output = Cmd::new("git")+/// .args(["status", "--porcelain"])+/// .current_dir(&repo_path)+/// .context("my-worktree")+/// .run()?;+/// ```+///+/// With stdin:+/// ```ignore+/// let output = Cmd::new("git")+/// .args(["diff-tree", "--stdin", "--numstat"])+/// .stdin(hashes.join("\n"))+/// .run()?;+/// ```+pub struct Cmd {+ program: String,+ args: Vec<String>,+ current_dir: Option<std::path::PathBuf>,+ context: Option<String>,+ stdin_data: Option<Vec<u8>>,+ timeout: Option<std::time::Duration>,+ envs: Vec<(String, String)>,+ env_removes: Vec<String>,+}++impl Cmd {+ /// Create a new command builder for the given program.+ pub fn new(program: impl Into<String>) -> Self {+ Self {+ program: program.into(),+ args: Vec::new(),+ current_dir: None,+ context: None,+ stdin_data: None,+ timeout: None,+ envs: Vec::new(),+ env_removes: Vec::new(),+ }+ }++ /// Add a single argument.+ pub fn arg(mut self, arg: impl Into<String>) -> Self {+ self.args.push(arg.into());+ self+ }++ /// Add multiple arguments.+ pub fn args<I, S>(mut self, args: I) -> Self+ where+ I: IntoIterator<Item = S>,+ S: Into<String>,+ {+ self.args.extend(args.into_iter().map(Into::into));+ self+ }++ /// Set the working directory for the command.+ pub fn current_dir(mut self, dir: impl Into<std::path::PathBuf>) -> Self {+ self.current_dir = Some(dir.into());+ self+ }++ /// Set the logging context (typically worktree name for git commands).+ pub fn context(mut self, ctx: impl Into<String>) -> Self {+ self.context = Some(ctx.into());+ self+ }++ /// Set data to write to the command's stdin.+ pub fn stdin(mut self, data: impl Into<Vec<u8>>) -> Self {+ self.stdin_data = Some(data.into());+ self+ }++ /// Set a timeout for command execution.+ pub fn timeout(mut self, duration: std::time::Duration) -> Self {+ self.timeout = Some(duration);+ self+ }++ /// Set an environment variable.+ pub fn env(mut self, key: impl Into<String>, val: impl Into<String>) -> Self {+ self.envs.push((key.into(), val.into()));+ self+ }++ /// Remove an environment variable.+ pub fn env_remove(mut self, key: impl Into<String>) -> Self {+ self.env_removes.push(key.into());+ self+ }++ /// Execute the command and return its output.+ ///+ /// Provides logging, semaphore limiting, and tracing like `run()`.+ pub fn run(self) -> std::io::Result<std::process::Output> {+ use std::io::Write;+ use std::process::Stdio;++ // Build command string for logging+ let cmd_str = if self.args.is_empty() {+ self.program.clone()+ } else {+ format!("{} {}", self.program, self.args.join(" "))+ };++ // Log command with optional context+ match &self.context {+ Some(ctx) => log::debug!("$ {} [{}]", cmd_str, ctx),+ None => log::debug!("$ {}", cmd_str),+ }++ // Acquire semaphore to limit concurrent commands+ let _guard = get_semaphore().acquire();++ // Capture timing for tracing+ let t0 = Instant::now();+ let ts = t0.duration_since(*trace_epoch()).as_micros() as u64;+ let tid = thread_id_number();++ // Build the Command+ let mut cmd = Command::new(&self.program);+ cmd.args(&self.args);+ cmd.env_remove(DIRECTIVE_FILE_ENV_VAR);++ if let Some(ref dir) = self.current_dir {+ cmd.current_dir(dir);+ }++ for (key, val) in &self.envs {+ cmd.env(key, val);+ }+ for key in &self.env_removes {+ cmd.env_remove(key);+ }++ // Determine effective timeout: explicit > thread-local > none+ let effective_timeout = self.timeout.or_else(|| COMMAND_TIMEOUT.with(|t| t.get()));++ // Execute with or without stdin+ let result = if let Some(stdin_data) = self.stdin_data {+ // Stdin piping requires spawn/write/wait+ // Note: stdin path doesn't support timeout (would need async I/O)+ cmd.stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped());++ let mut child = cmd.spawn()?;++ // Write stdin data (ignore BrokenPipe - some commands exit early)+ if let Some(mut stdin) = child.stdin.take()+ && let Err(e) = stdin.write_all(&stdin_data)+ && e.kind() != std::io::ErrorKind::BrokenPipe+ {+ return Err(e);+ }++ child.wait_with_output()+ } else if let Some(timeout_duration) = effective_timeout {+ // Timeout handling uses the existing impl+ run_with_timeout_impl(&mut cmd, timeout_duration)+ } else {+ // Simple case: just run and capture output+ cmd.output()+ };++ // Log trace+ let dur_us = t0.elapsed().as_micros() as u64;+ match (&result, &self.context) {+ (Ok(output), Some(ctx)) => {+ log::debug!(+ "[wt-trace] ts={} tid={} context={} cmd=\"{}\" dur_us={} ok={}",+ ts,+ tid,+ ctx,+ cmd_str,+ dur_us,+ output.status.success()+ );+ }+ (Ok(output), None) => {+ log::debug!(+ "[wt-trace] ts={} tid={} cmd=\"{}\" dur_us={} ok={}",+ ts,+ tid,+ cmd_str,+ dur_us,+ output.status.success()+ );+ }+ (Err(e), Some(ctx)) => {+ log::debug!(+ "[wt-trace] ts={} tid={} context={} cmd=\"{}\" dur_us={} err=\"{}\"",+ ts,+ tid,+ ctx,+ cmd_str,+ dur_us,+ e+ );+ }+ (Err(e), None) => {+ log::debug!(+ "[wt-trace] ts={} tid={} cmd=\"{}\" dur_us={} err=\"{}\"",+ ts,+ tid,+ cmd_str,+ dur_us,+ e+ );+ }+ }++ result+ }+}+// ============================================================================// Streaming command execution with signal handling// ============================================================================@@ -796,14 +902,15 @@ mod tests {}// ========================================================================- // Timeout tests+ // Cmd and timeout tests// ========================================================================#[test]- fn test_run_with_timeout_completes_fast_command() {- let mut cmd = Command::new("echo");- cmd.arg("hello");- let result = run_with_timeout(&mut cmd, None, Some(Duration::from_secs(5)));+ fn test_cmd_completes_fast_command() {+ let result = Cmd::new("echo")+ .arg("hello")+ .timeout(Duration::from_secs(5))+ .run();assert!(result.is_ok());let output = result.unwrap();assert!(output.status.success());@@ -812,27 +919,43 @@ mod tests {#[test]#[cfg(unix)]- fn test_run_with_timeout_kills_slow_command() {- let mut cmd = Command::new("sleep");- cmd.arg("10");- let result = run_with_timeout(&mut cmd, None, Some(Duration::from_millis(50)));+ fn test_cmd_timeout_kills_slow_command() {+ let result = Cmd::new("sleep")+ .arg("10")+ .timeout(Duration::from_millis(50))+ .run();assert!(result.is_err());assert_eq!(result.unwrap_err().kind(), std::io::ErrorKind::TimedOut);}#[test]- fn test_run_with_no_timeout_completes() {- let mut cmd = Command::new("echo");- cmd.arg("no timeout");- let result = run_with_timeout(&mut cmd, None, None);+ fn test_cmd_without_timeout_completes() {+ let result = Cmd::new("echo").arg("no timeout").run();assert!(result.is_ok());}+ #[test]+ fn test_cmd_with_context() {+ let result = Cmd::new("echo")+ .arg("with context")+ .context("test-context")+ .run();+ assert!(result.is_ok());+ }++ #[test]+ fn test_cmd_with_stdin() {+ let result = Cmd::new("cat").stdin("hello from stdin").run();+ assert!(result.is_ok());+ let output = result.unwrap();+ assert!(output.status.success());+ assert!(String::from_utf8_lossy(&output.stdout).contains("hello from stdin"));+ }+#[test]fn test_thread_local_timeout_setting() {- // Initially no timeout+ // Initially no timeout (or whatever was set by previous test)let initial = COMMAND_TIMEOUT.with(|t| t.get());- assert!(initial.is_none() || initial == Some(Duration::from_millis(500)));// Set a timeoutset_command_timeout(Some(Duration::from_millis(100)));@@ -840,22 +963,37 @@ mod tests {assert_eq!(after_set, Some(Duration::from_millis(100)));// Clear the timeout- set_command_timeout(None);+ set_command_timeout(initial);let after_clear = COMMAND_TIMEOUT.with(|t| t.get());- assert!(after_clear.is_none());+ assert_eq!(after_clear, initial);}#[test]- fn test_run_uses_thread_local_timeout() {+ fn test_cmd_uses_thread_local_timeout() {// Set no timeout (ensure fast completion)set_command_timeout(None);- let mut cmd = Command::new("echo");- cmd.arg("thread local test");- let result = run(&mut cmd, None);+ let result = Cmd::new("echo").arg("thread local test").run();assert!(result.is_ok());// Clean upset_command_timeout(None);}++ #[test]+ #[cfg(unix)]+ fn test_cmd_thread_local_timeout_kills_slow_command() {+ // Set a short thread-local timeout+ set_command_timeout(Some(Duration::from_millis(50)));++ // Command that would take too long+ let result = Cmd::new("sleep").arg("10").run();++ // Should be killed by the thread-local timeout+ assert!(result.is_err());+ assert_eq!(result.unwrap_err().kind(), std::io::ErrorKind::TimedOut);++ // Clean up+ set_command_timeout(None);+ }}diff --git a/src/trace/parse.rs b/src/trace/parse.rsindex 9a37b4e5e..2d1c2ac8d 100644--- a/src/trace/parse.rs+++ b/src/trace/parse.rs@@ -1,6 +1,6 @@//! Parse wt-trace log lines into structured entries.//!-//! Trace lines are emitted by `shell_exec::run()` with this format:+//! Trace lines are emitted by `shell_exec::Cmd` with this format://! ```text//! [wt-trace] ts=1234567 tid=3 context=worktree cmd="git status" dur_us=12300 ok=true//! [wt-trace] ts=1234567 tid=3 cmd="gh pr list" dur_us=45200 ok=false