Skip to main content

git_worktree_manager/operations/
run.rs

1//! `gw run <cmd>` — fan a command out across all worktrees in scope.
2
3use std::io::Write;
4use std::path::Path;
5use std::process::Command;
6
7use crate::error::Result;
8use crate::scope;
9
10pub fn run_in_scope(
11    cwd: &Path,
12    cmd: &[String],
13    only: Option<&str>,
14    no_main: bool,
15    jobs: usize,
16    continue_on_error: bool,
17) -> Result<i32> {
18    let mut stdout = std::io::stdout().lock();
19    run_in_scope_to_writer(
20        cwd,
21        cmd,
22        only,
23        no_main,
24        jobs,
25        continue_on_error,
26        &mut stdout,
27    )
28}
29
30/// Returns the last non-zero exit code observed (or 0 if all succeeded).
31/// In parallel mode (`jobs > 1`), `continue_on_error = false` aborts at batch
32/// boundaries — siblings already started in the same batch run to completion.
33pub fn run_in_scope_to_writer<W: Write>(
34    cwd: &Path,
35    cmd: &[String],
36    only: Option<&str>,
37    no_main: bool,
38    jobs: usize,
39    continue_on_error: bool,
40    out: &mut W,
41) -> Result<i32> {
42    let scope = scope::discover_scope(cwd)?;
43    let mut targets: Vec<&scope::ScopedWorktree> = scope
44        .worktrees()
45        .iter()
46        .filter(|w| !no_main || !w.is_main)
47        .filter(|w| match only {
48            // Match against either the branch name (what users type) or the
49            // worktree directory basename (path layout). Branch is checked
50            // first because it's the natural identifier — `gw ls`, target
51            // resolution, and the Quick Start examples all use it.
52            Some(g) => {
53                w.branch
54                    .as_deref()
55                    .map(|b| glob_match(g, b))
56                    .unwrap_or(false)
57                    || glob_match(g, &w.name)
58            }
59            None => true,
60        })
61        .collect();
62    targets.sort_by_key(|w| (!w.is_main, w.name.clone())); // main first
63
64    let jobs = jobs.max(1);
65    let mut last_failure: i32 = 0;
66    let mut i = 0;
67    while i < targets.len() {
68        let batch_end = (i + jobs).min(targets.len());
69
70        // Spawn each child in this batch on its own thread, capturing
71        // (target_index, captured_output, exit_code).
72        let handles: Vec<std::thread::JoinHandle<Result<(usize, String, i32)>>> = (i..batch_end)
73            .map(|k| {
74                let w = targets[k];
75                let name = w.name.clone();
76                let path = w.path.clone();
77                let cmd_v: Vec<String> = cmd.to_vec();
78                std::thread::spawn(move || {
79                    let (s, code) = run_capture_one(&name, &path, &cmd_v)?;
80                    Ok((k, s, code))
81                })
82            })
83            .collect();
84
85        // Collect, then sort by target index so output is emitted in target order
86        // (NOT completion order). This preserves the "main first, then alphabetical"
87        // ordering established by the earlier sort_by_key.
88        let mut results: Vec<(usize, String, i32)> = handles
89            .into_iter()
90            .map(|h| h.join().expect("worker panicked"))
91            .collect::<Result<Vec<_>>>()?;
92        results.sort_by_key(|(k, _, _)| *k);
93
94        for (_, s, code) in results {
95            let _ = out.write_all(s.as_bytes());
96            if code != 0 {
97                last_failure = code;
98                if !continue_on_error {
99                    return Ok(last_failure);
100                }
101            }
102        }
103        i = batch_end;
104    }
105    Ok(last_failure)
106}
107
108pub(crate) fn run_capture_one(name: &str, path: &Path, cmd: &[String]) -> Result<(String, i32)> {
109    let prefix = format!("[{}] ", name);
110    let mut child = Command::new(&cmd[0])
111        .args(&cmd[1..])
112        .current_dir(path)
113        .stdout(std::process::Stdio::piped())
114        .stderr(std::process::Stdio::piped())
115        .spawn()?;
116    let stdout = child.stdout.take().expect("piped stdout");
117    let stderr = child.stderr.take().expect("piped stderr");
118
119    let prefix_a = prefix.clone();
120    let h1 = std::thread::spawn(move || pipe_with_prefix(stdout, &prefix_a));
121    let prefix_b = prefix.clone();
122    let h2 = std::thread::spawn(move || pipe_with_prefix(stderr, &prefix_b));
123
124    let so = h1.join().unwrap_or_default();
125    let se = h2.join().unwrap_or_default();
126    let mut combined = so;
127    combined.push_str(&se);
128
129    let status = child.wait()?;
130    Ok((combined, status.code().unwrap_or(1)))
131}
132
133fn pipe_with_prefix<R: std::io::Read>(reader: R, prefix: &str) -> String {
134    use std::io::BufRead;
135    let buf = std::io::BufReader::new(reader);
136    let mut out = String::new();
137    for line in buf.lines().map_while(|l| l.ok()) {
138        out.push_str(prefix);
139        out.push_str(&line);
140        out.push('\n');
141    }
142    out
143}
144
145fn glob_match(pattern: &str, name: &str) -> bool {
146    // Empty pattern matches only empty name.
147    if pattern.is_empty() {
148        return name.is_empty();
149    }
150    // Minimal glob: supports '*' anywhere. No '?', no character classes.
151    let parts: Vec<&str> = pattern.split('*').collect();
152    let mut idx = 0usize;
153    let last = parts.len() - 1;
154    if !pattern.starts_with('*') && !name.starts_with(parts[0]) {
155        return false;
156    }
157    for (i, part) in parts.iter().enumerate() {
158        if part.is_empty() {
159            continue;
160        }
161        // For the last segment when the pattern is not '*'-terminated, use
162        // rfind so that the trailing literal is anchored to end-of-string
163        // rather than matching the first occurrence in the remaining slice.
164        let pos = if i == last && !pattern.ends_with('*') {
165            name[idx..].rfind(part)
166        } else {
167            name[idx..].find(part)
168        };
169        match pos {
170            Some(p) => idx += p + part.len(),
171            None => return false,
172        }
173        if i == last && !pattern.ends_with('*') && idx != name.len() {
174            return false;
175        }
176    }
177    true
178}
179
180#[cfg(test)]
181mod glob_tests {
182    use super::glob_match;
183
184    #[test]
185    fn empty_pattern_matches_only_empty() {
186        assert!(glob_match("", ""));
187        assert!(!glob_match("", "anything"));
188    }
189
190    #[test]
191    fn star_matches_anything() {
192        assert!(glob_match("*", ""));
193        assert!(glob_match("*", "anything"));
194    }
195
196    #[test]
197    fn literal_matches_exactly() {
198        assert!(glob_match("foo", "foo"));
199        assert!(!glob_match("foo", "foobar"));
200        assert!(!glob_match("foo", "barfoo"));
201        assert!(!glob_match("foo", "fo"));
202    }
203
204    #[test]
205    fn leading_star() {
206        assert!(glob_match("*foo", "foo"));
207        assert!(glob_match("*foo", "barfoo"));
208        assert!(!glob_match("*foo", "foobar"));
209    }
210
211    #[test]
212    fn trailing_star() {
213        assert!(glob_match("foo*", "foo"));
214        assert!(glob_match("foo*", "foobar"));
215        assert!(!glob_match("foo*", "barfoo"));
216    }
217
218    #[test]
219    fn double_star_collapses() {
220        // Adjacent '*' is harmless — empty parts skip in the loop.
221        assert!(glob_match("**foo", "foo"));
222        assert!(glob_match("foo**bar", "foobar"));
223    }
224
225    #[test]
226    fn middle_star() {
227        assert!(glob_match("a*b", "ab"));
228        assert!(glob_match("a*b", "axb"));
229        assert!(!glob_match("a*b", "axc"));
230    }
231
232    #[test]
233    fn trailing_literal_anchored_to_end_with_repeated_substring() {
234        // The bug-fix case: trailing literal must rfind, not find.
235        assert!(glob_match("*a*a", "aaaa"));
236        assert!(glob_match("*a", "aaaa"));
237        assert!(!glob_match("*a", "aaab"));
238    }
239
240    #[test]
241    fn realistic_feat_glob() {
242        assert!(glob_match("feat-*", "feat-login"));
243        assert!(glob_match("feat-*", "feat-"));
244        assert!(!glob_match("feat-*", "bug-feat-x"));
245    }
246}