Skip to main content

thor_wt/
exec.rs

1use thor_core::{find_repo, list_worktrees};
2use std::path::PathBuf;
3use std::process::Command;
4
5/// Result of running a command in one worktree.
6pub struct ExecResult {
7    pub branch: String,
8    pub path: PathBuf,
9    pub exit_code: i32,
10    pub output: String,
11}
12
13/// Run a shell command in every worktree.
14///
15/// The command is passed to `sh -c` for shell expansion.
16/// This is intentional — the user provides the command string
17/// directly via `thor wt exec <cmd>`, similar to `git worktree foreach`.
18pub async fn exec(command: &str) -> anyhow::Result<Vec<ExecResult>> {
19    let repo = find_repo()?;
20    let worktrees = list_worktrees(&repo).await?;
21    let mut results = Vec::new();
22
23    for wt in &worktrees {
24        let output = Command::new("sh")
25            .args(["-c", command])
26            .current_dir(&wt.path)
27            .output()?;
28
29        let combined = format!(
30            "{}{}",
31            String::from_utf8_lossy(&output.stdout),
32            String::from_utf8_lossy(&output.stderr),
33        );
34
35        results.push(ExecResult {
36            branch: wt.display_name(),
37            path: wt.path.clone(),
38            exit_code: output.status.code().unwrap_or(-1),
39            output: combined,
40        });
41    }
42
43    Ok(results)
44}