Skip to content

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

Unify command execution through shell_exec::run() (#232)

Maximilian Roos403592ae0bb1
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 5f1d4a1f9..719fb34da 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -67,6 +67,16 @@ repos:
language: pygrep
entry: '\.canonicalize\(\)'
files: '^tests/'
+ - id: no-direct-cmd-output
+ name: no-direct-cmd-output
+ description: Use shell_exec::run() instead of cmd.output() for consistent logging
+ language: pygrep
+ types: ["rust"]
+ entry: '\.output\(\)'
+ # shell_exec.rs: defines run() which legitimately calls .output()
+ # select.rs: skim API's selected.output() is not Command::output()
+ # tests/benches: test utilities run commands directly
+ exclude: '^(src/shell_exec\.rs|src/commands/select\.rs|tests/|benches/)'
ci:
# pre-commit.ci doesn't have Rust toolchain, so skip Rust-specific hooks.
diff --git a/CLAUDE.md b/CLAUDE.md
index c3ca99dbf..e58cd0ada 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -95,6 +95,25 @@ The pre-merge hook already sets `NEXTEST_NO_INPUT_HANDLER=1`.
## Command Execution Principles
+### All Commands Through `shell_exec::run`
+
+All external command execution must go through `shell_exec::run()`. This ensures consistent logging and tracing for every command:
+
+```rust
+use crate::shell_exec::run;
+
+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
+```
+
+Never use `cmd.output()` directly. The `run()` function provides:
+- Debug logging: `$ git status [worktree-name]`
+- Timing traces: `[wt-trace] cmd="..." dur=12.3ms ok=true`
+
+For git commands, use `Repository::run_command()` which wraps `shell_exec::run` with worktree context.
+
### Real-time Output Streaming
Command output must stream in real-time. Never buffer external command output.
diff --git a/src/commands/list/ci_status.rs b/src/commands/list/ci_status.rs
index 76422b65e..63c0edfa2 100644
--- a/src/commands/list/ci_status.rs
+++ b/src/commands/list/ci_status.rs
@@ -1,6 +1,7 @@
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use std::process::Command;
use worktrunk::git::Repository;
+use worktrunk::shell_exec::run;
/// CI platform detected from remote URL
// TODO: Add a `[ci] platform = "github" | "gitlab"` override in project config
@@ -31,11 +32,10 @@ pub fn get_platform_for_repo(repo_root: &str) -> Option<CiPlatform> {
/// Get the origin remote URL for a repository.
fn get_remote_url_for_repo(repo_root: &str) -> Option<String> {
- let output = Command::new("git")
- .args(["remote", "get-url", "origin"])
- .current_dir(repo_root)
- .output()
- .ok()?;
+ let mut cmd = Command::new("git");
+ cmd.args(["remote", "get-url", "origin"])
+ .current_dir(repo_root);
+ let output = run(&mut cmd, None).ok()?;
if output.status.success() {
String::from_utf8(output.stdout).ok()
@@ -772,11 +772,10 @@ const MAX_PRS_TO_FETCH: u8 = 20;
/// Used for client-side filtering of PRs by source repository.
/// See [`parse_remote_owner`] for details on why this is necessary.
fn get_origin_owner(repo_root: &str) -> Option<String> {
- let output = Command::new("git")
- .args(["remote", "get-url", "origin"])
- .current_dir(repo_root)
- .output()
- .ok()?;
+ let mut cmd = Command::new("git");
+ cmd.args(["remote", "get-url", "origin"])
+ .current_dir(repo_root);
+ let output = run(&mut cmd, None).ok()?;
if output.status.success() {
let url = String::from_utf8(output.stdout).ok()?;
parse_remote_owner(&url).map(|s| s.to_string())
@@ -807,7 +806,7 @@ fn get_gitlab_project_id(repo_root: &str) -> Option<u64> {
disable_color_output(&mut cmd);
cmd.env("PAGER", "cat");
- let output = cmd.output().ok()?;
+ let output = run(&mut cmd, None).ok()?;
if !output.status.success() {
return None;
@@ -838,28 +837,22 @@ fn disable_color_output(cmd: &mut Command) {
/// that may be in PATH, since Rust's Command::new doesn't search PATHEXT.
fn tool_available(tool: &str, args: &[&str]) -> bool {
#[cfg(windows)]
- {
- // Build command string: "tool arg1 arg2..."
- let mut cmd_str = tool.to_string();
- for arg in args {
- cmd_str.push(' ');
- cmd_str.push_str(arg);
- }
-
- Command::new("cmd")
- .args(["/c", &cmd_str])
- .output()
- .map(|o| o.status.success())
- .unwrap_or(false)
- }
+ let mut cmd = {
+ let cmd_str = format!("{} {}", tool, args.join(" "));
+ let mut c = Command::new("cmd");
+ c.args(["/c", &cmd_str]);
+ c
+ };
#[cfg(not(windows))]
- {
- Command::new(tool)
- .args(args)
- .output()
- .map(|o| o.status.success())
- .unwrap_or(false)
- }
+ let mut cmd = {
+ let mut c = Command::new(tool);
+ c.args(args);
+ c
+ };
+
+ run(&mut cmd, None)
+ .map(|o| o.status.success())
+ .unwrap_or(false)
}
/// Status of CI tools availability
@@ -1029,11 +1022,10 @@ impl CachedCiStatus {
"worktrunk.ci.{}",
worktrunk::git::escape_branch_for_config(branch)
);
- let output = Command::new("git")
- .args(["config", "--get", &config_key])
- .current_dir(repo_root)
- .output()
- .ok()?;
+ let mut cmd = Command::new("git");
+ cmd.args(["config", "--get", &config_key])
+ .current_dir(repo_root);
+ let output = run(&mut cmd, None).ok()?;
if !output.status.success() {
return None;
@@ -1053,11 +1045,10 @@ impl CachedCiStatus {
log::debug!("Failed to serialize CI cache for {}", branch);
return;
};
- if let Err(e) = Command::new("git")
- .args(["config", &config_key, &json])
- .current_dir(repo_root)
- .output()
- {
+ let mut cmd = Command::new("git");
+ cmd.args(["config", &config_key, &json])
+ .current_dir(repo_root);
+ if let Err(e) = run(&mut cmd, None) {
log::debug!("Failed to write CI cache for {}: {}", branch, e);
}
}
@@ -1316,8 +1307,9 @@ impl PrStatus {
/// - Multiple users with same branch name
fn detect_github(branch: &str, local_head: &str, repo_root: &str) -> Option<Self> {
// Check if gh is available and authenticated
- let auth = Command::new("gh").args(["auth", "status"]).output();
- match auth {
+ let mut auth_cmd = Command::new("gh");
+ auth_cmd.args(["auth", "status"]);
+ match run(&mut auth_cmd, None) {
Err(e) => {
log::debug!("gh not available for {}: {}", branch, e);
return None;
@@ -1358,7 +1350,7 @@ impl PrStatus {
disable_color_output(&mut cmd);
cmd.current_dir(repo_root);
- let output = match cmd.output() {
+ let output = match run(&mut cmd, None) {
Ok(output) => output,
Err(e) => {
log::warn!("gh pr list failed to execute for branch {}: {}", branch, e);
@@ -1368,7 +1360,6 @@ impl PrStatus {
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
- log::debug!("gh pr list failed for {}: {}", branch, stderr.trim());
if is_retriable_error(&stderr) {
return Some(Self::error());
}
@@ -1466,7 +1457,7 @@ impl PrStatus {
]);
cmd.current_dir(repo_root);
- let output = match cmd.output() {
+ let output = match run(&mut cmd, None) {
Ok(output) => output,
Err(e) => {
log::warn!(
@@ -1480,7 +1471,6 @@ impl PrStatus {
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
- log::debug!("glab mr list failed for {}: {}", branch, stderr.trim());
// Return error status for retriable failures (rate limit, network) so they
// surface as warnings instead of being cached as "no CI"
if is_retriable_error(&stderr) {
@@ -1563,7 +1553,7 @@ impl PrStatus {
disable_color_output(&mut cmd);
cmd.current_dir(repo_root);
- let output = match cmd.output() {
+ let output = match run(&mut cmd, None) {
Ok(output) => output,
Err(e) => {
log::warn!("gh run list failed to execute for branch {}: {}", branch, e);
@@ -1573,7 +1563,6 @@ impl PrStatus {
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
- log::debug!("gh run list failed for {}: {}", branch, stderr.trim());
if is_retriable_error(&stderr) {
return Some(Self::error());
}
@@ -1607,11 +1596,11 @@ impl PrStatus {
}
// Get most recent pipeline for the branch using JSON output
- let output = match Command::new("glab")
- .args(["ci", "list", "--per-page", "1", "--output", "json"])
- .env("BRANCH", branch) // glab ci list uses BRANCH env var
- .output()
- {
+ let mut cmd = Command::new("glab");
+ cmd.args(["ci", "list", "--per-page", "1", "--output", "json"])
+ .env("BRANCH", branch); // glab ci list uses BRANCH env var
+
+ let output = match run(&mut cmd, None) {
Ok(output) => output,
Err(e) => {
log::warn!(
@@ -1624,8 +1613,6 @@ impl PrStatus {
};
if !output.status.success() {
- let stderr = String::from_utf8_lossy(&output.stderr);
- log::debug!("glab ci list failed for {}: {}", branch, stderr.trim());
return None;
}
diff --git a/src/commands/list/mod.rs b/src/commands/list/mod.rs
index f1821a615..08bdd4b40 100644
--- a/src/commands/list/mod.rs
+++ b/src/commands/list/mod.rs
@@ -201,61 +201,72 @@ pub fn handle_list(
}
}
- // Show hint if CI status was requested but no tools can fetch it
+ // Show hint if CI status was requested but no tools can fetch it.
+ // Skip the check if any items already have CI status (tools must be available).
if show_full {
- // Check auth status against the specific GitLab host for this repo
- let gitlab_host = repo
- .worktree_root()
- .ok()
- .and_then(|p| p.to_str().map(|s| s.to_string()))
- .and_then(|p| ci_status::get_gitlab_host_for_repo(&p));
- let ci_tools = ci_status::CiToolsStatus::detect(gitlab_host.as_deref());
- if !ci_tools.any_available() {
- use ci_status::{CiPlatform, get_platform_for_repo};
- use color_print::cformat;
- use worktrunk::git::Repository;
- use worktrunk::styling::hint_message;
-
- // Detect platform from repo's remote URL
- let platform = Repository::current()
+ // pr_status semantics: None = not fetched, Some(None) = fetched but no PR,
+ // Some(Some(status)) = fetched with status. If any item is Some(_), we
+ // successfully communicated with CI tools, so they're available.
+ let any_ci_fetched = items.iter().any(|item| item.pr_status.is_some());
+
+ if any_ci_fetched {
+ log::debug!("Skipping CI tools detection - CI status already fetched");
+ } else {
+ // No CI was fetched - run full detection to show helpful hint
+ let gitlab_host = repo
.worktree_root()
.ok()
- .and_then(|root| get_platform_for_repo(root.to_str()?));
-
- // Only show hint for the relevant platform's tool
- let hint = match platform {
- Some(CiPlatform::GitHub) => {
- if ci_tools.gh_installed && !ci_tools.gh_authenticated {
- Some(cformat!(
- "CI status unavailable; run <bright-black>gh auth login</> to authenticate"
- ))
- } else if !ci_tools.gh_installed {
- Some(cformat!(
- "CI status unavailable; install <bright-black>gh</>"
- ))
- } else {
- None
+ .and_then(|p| p.to_str().map(|s| s.to_string()))
+ .and_then(|p| ci_status::get_gitlab_host_for_repo(&p));
+ let ci_tools = ci_status::CiToolsStatus::detect(gitlab_host.as_deref());
+
+ if !ci_tools.any_available() {
+ use ci_status::{CiPlatform, get_platform_for_repo};
+ use color_print::cformat;
+ use worktrunk::git::Repository;
+ use worktrunk::styling::hint_message;
+
+ // Detect platform from repo's remote URL
+ let platform = Repository::current()
+ .worktree_root()
+ .ok()
+ .and_then(|root| get_platform_for_repo(root.to_str()?));
+
+ // Only show hint for the relevant platform's tool
+ let hint = match platform {
+ Some(CiPlatform::GitHub) => {
+ if ci_tools.gh_installed && !ci_tools.gh_authenticated {
+ Some(cformat!(
+ "CI status unavailable; run <bright-black>gh auth login</> to authenticate"
+ ))
+ } else if !ci_tools.gh_installed {
+ Some(cformat!(
+ "CI status unavailable; install <bright-black>gh</>"
+ ))
+ } else {
+ None
+ }
}
- }
- Some(CiPlatform::GitLab) => {
- if ci_tools.glab_installed && !ci_tools.glab_authenticated {
- Some(cformat!(
- "CI status unavailable; run <bright-black>glab auth login</> to authenticate"
- ))
- } else if !ci_tools.glab_installed {
- Some(cformat!(
- "CI status unavailable; install <bright-black>glab</>"
- ))
- } else {
- None
+ Some(CiPlatform::GitLab) => {
+ if ci_tools.glab_installed && !ci_tools.glab_authenticated {
+ Some(cformat!(
+ "CI status unavailable; run <bright-black>glab auth login</> to authenticate"
+ ))
+ } else if !ci_tools.glab_installed {
+ Some(cformat!(
+ "CI status unavailable; install <bright-black>glab</>"
+ ))
+ } else {
+ None
+ }
}
- }
- None => None, // Unknown platform - don't show any hint
- };
+ None => None, // Unknown platform - don't show any hint
+ };
- if let Some(message) = hint {
- crate::output::blank()?;
- crate::output::print(hint_message(message))?;
+ if let Some(message) = hint {
+ crate::output::blank()?;
+ crate::output::print(hint_message(message))?;
+ }
}
}
}
diff --git a/src/commands/select.rs b/src/commands/select.rs
index 07df3f70b..f7a87c0e9 100644
--- a/src/commands/select.rs
+++ b/src/commands/select.rs
@@ -9,6 +9,7 @@ use std::sync::{Arc, OnceLock};
use std::time::{Duration, Instant};
use worktrunk::config::WorktrunkConfig;
use worktrunk::git::Repository;
+use worktrunk::shell_exec::run;
use super::list::collect;
use super::list::layout::{DiffDisplayConfig, DiffVariant};
@@ -38,19 +39,17 @@ fn get_diff_pager() -> Option<&'static String> {
}
// Fall back to core.pager config
- Command::new("git")
- .args(["config", "--get", "core.pager"])
- .output()
- .ok()
- .and_then(|output| {
- if output.status.success() {
- String::from_utf8(output.stdout)
- .ok()
- .and_then(|s| parse_pager(&s))
- } else {
- None
- }
- })
+ let mut cmd = Command::new("git");
+ cmd.args(["config", "--get", "core.pager"]);
+ run(&mut cmd, None).ok().and_then(|output| {
+ if output.status.success() {
+ String::from_utf8(output.stdout)
+ .ok()
+ .and_then(|s| parse_pager(&s))
+ } else {
+ None
+ }
+ })
})
.as_ref()
}
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index fbade769f..244ebd87d 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -1479,6 +1479,21 @@ impl Repository {
Ok(repo_name.to_string())
}
+ /// Get a short display name for this repository, used in logging context.
+ ///
+ /// Returns "." for the current directory, or the directory name otherwise.
+ fn logging_context(&self) -> String {
+ if self.path.to_str() == Some(".") {
+ ".".to_string()
+ } else {
+ self.path
+ .file_name()
+ .and_then(|n| n.to_str())
+ .unwrap_or("?")
+ .to_string()
+ }
+ }
+
/// Run a git command in this repository's context.
///
/// Executes the git command with this repository's path as the working directory
@@ -1493,40 +1508,14 @@ impl Repository {
/// # Ok::<(), anyhow::Error>(())
/// ```
pub fn run_command(&self, args: &[&str]) -> anyhow::Result<String> {
- use std::time::Instant;
+ use crate::shell_exec::run;
let mut cmd = Command::new("git");
cmd.args(args);
cmd.current_dir(&self.path);
- // Log: $ git <args> [worktree]
- // TODO: Guard with log::log_enabled! if args.join() overhead becomes measurable
- let worktree_name = if self.path.to_str() == Some(".") {
- log::debug!("$ git {}", args.join(" "));
- ".".to_string()
- } else {
- let worktree = self
- .path
- .file_name()
- .and_then(|n| n.to_str())
- .unwrap_or("?");
- log::debug!("$ git {} [{}]", args.join(" "), worktree);
- worktree.to_string()
- };
-
- let t0 = Instant::now();
- let output = cmd
- .output()
+ let output = run(&mut cmd, Some(&self.logging_context()))
.with_context(|| format!("Failed to execute: git {}", args.join(" ")))?;
- let duration = t0.elapsed();
-
- // Performance tracing at debug level (enable with RUST_LOG=debug)
- log::debug!(
- "[wt-trace] worktree={} cmd=\"git {}\" dur={:.1}ms",
- worktree_name,
- args.join(" "),
- duration.as_secs_f64() * 1e3
- );
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
@@ -1571,31 +1560,16 @@ impl Repository {
/// # Ok::<(), anyhow::Error>(())
/// ```
pub fn run_command_check(&self, args: &[&str]) -> anyhow::Result<bool> {
+ use crate::shell_exec::run;
+
let mut cmd = Command::new("git");
cmd.args(args);
cmd.current_dir(&self.path);
- // Log: $ git <args> [worktree]
- if self.path.to_str() == Some(".") {
- log::debug!("$ git {}", args.join(" "));
- } else {
- let worktree = self
- .path
- .file_name()
- .and_then(|n| n.to_str())
- .unwrap_or("?");
- log::debug!("$ git {} [{}]", args.join(" "), worktree);
- }
-
- let output = cmd
- .output()
+ let output = run(&mut cmd, Some(&self.logging_context()))
.with_context(|| format!("Failed to execute: git {}", args.join(" ")))?;
- let success = output.status.success();
- if !success {
- log::debug!(" → exit code: non-zero");
- }
- Ok(success)
+ Ok(output.status.success())
}
}
diff --git a/src/help_pager.rs b/src/help_pager.rs
index 01c617e8c..d3b3c0000 100644
--- a/src/help_pager.rs
+++ b/src/help_pager.rs
@@ -22,7 +22,7 @@
use std::io::{IsTerminal, Write};
use std::process::{Command, Stdio};
-use worktrunk::shell_exec::ShellConfig;
+use worktrunk::shell_exec::{ShellConfig, run};
fn validate_pager(s: &str) -> Option<String> {
let trimmed = s.trim();
@@ -44,20 +44,17 @@ fn detect_help_pager() -> Option<String> {
.and_then(|s| validate_pager(&s))
.or_else(|| {
// Try git config core.pager
- Command::new("git")
- .args(["config", "--get", "core.pager"])
- .output()
- .inspect_err(|e| log::debug!("Failed to run git config: {}", e))
- .ok()
- .and_then(|output| {
- if !output.status.success() {
- log::debug!("git config exited with status: {}", output.status);
- }
- String::from_utf8(output.stdout)
- .inspect_err(|e| log::debug!("git config output not UTF-8: {}", e))
- .ok()
- .and_then(|s| validate_pager(&s))
- })
+ let mut cmd = Command::new("git");
+ cmd.args(["config", "--get", "core.pager"]);
+ run(&mut cmd, None).ok().and_then(|output| {
+ if !output.status.success() {
+ return None;
+ }
+ String::from_utf8(output.stdout)
+ .inspect_err(|e| log::debug!("git config output not UTF-8: {}", e))
+ .ok()
+ .and_then(|s| validate_pager(&s))
+ })
})
.or_else(|| std::env::var("PAGER").ok().and_then(|s| validate_pager(&s)));
diff --git a/src/path.rs b/src/path.rs
index 9702ef354..7eefc6b28 100644
--- a/src/path.rs
+++ b/src/path.rs
@@ -1,5 +1,7 @@
use std::path::{Path, PathBuf};
+#[cfg(windows)]
+use crate::shell_exec::run;
#[cfg(windows)]
use std::process::Command;
@@ -26,7 +28,9 @@ pub fn to_posix_path(path: &str) -> String {
return path.to_string();
};
- let Ok(output) = Command::new(&cygpath).arg("-u").arg(path).output() else {
+ let mut cmd = Command::new(&cygpath);
+ cmd.arg("-u").arg(path);
+ let Ok(output) = run(&mut cmd, None) else {
return path.to_string();
};
diff --git a/src/shell_exec.rs b/src/shell_exec.rs
index 5c4b8da69..e648dd544 100644
--- a/src/shell_exec.rs
+++ b/src/shell_exec.rs
@@ -178,6 +178,82 @@ fn find_git_bash() -> Option<PathBuf> {
None
}
+/// 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.
+///
+/// ```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> {
+ use std::time::Instant;
+
+ // 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),
+ }
+
+ let t0 = Instant::now();
+ let result = cmd.output();
+ let duration_ms = t0.elapsed().as_secs_f64() * 1000.0;
+
+ // Log trace with timing
+ match (&result, context) {
+ (Ok(output), Some(ctx)) => {
+ log::debug!(
+ "[wt-trace] context={} cmd=\"{}\" dur={:.1}ms ok={}",
+ ctx,
+ cmd_str,
+ duration_ms,
+ output.status.success()
+ );
+ }
+ (Ok(output), None) => {
+ log::debug!(
+ "[wt-trace] cmd=\"{}\" dur={:.1}ms ok={}",
+ cmd_str,
+ duration_ms,
+ output.status.success()
+ );
+ }
+ (Err(e), Some(ctx)) => {
+ log::debug!(
+ "[wt-trace] context={} cmd=\"{}\" dur={:.1}ms err=\"{}\"",
+ ctx,
+ cmd_str,
+ duration_ms,
+ e
+ );
+ }
+ (Err(e), None) => {
+ log::debug!(
+ "[wt-trace] cmd=\"{}\" dur={:.1}ms err=\"{}\"",
+ cmd_str,
+ duration_ms,
+ e
+ );
+ }
+ }
+
+ result
+}
+
#[cfg(test)]
mod tests {
use super::*;