Skip to main content

blyte_cli/
setup.rs

1//! Prepares a dispatch worktree's environment before the implementer starts.
2
3use std::collections::BTreeMap;
4use std::path::{Path, PathBuf};
5use std::time::Duration;
6
7use blyte_agent::shell::Shell;
8
9pub const SETUP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(600);
10
11fn quote(s: &str) -> String {
12    format!("'{}'", s.replace('\'', r"'\''"))
13}
14
15fn absolute_log_path(
16    log_path: &Path,
17    get_cwd: impl FnOnce() -> std::io::Result<PathBuf>,
18) -> Result<PathBuf, String> {
19    if log_path.is_absolute() {
20        Ok(log_path.to_path_buf())
21    } else {
22        get_cwd().map(|cwd| cwd.join(log_path)).map_err(|e| {
23            format!(
24                "failed to resolve absolute setup log path for {} (current working directory unavailable): {e}",
25                log_path.display()
26            )
27        })
28    }
29}
30
31fn write_setup_log(log_path: &Path, content: &str) -> Result<(), String> {
32    if let Some(parent) = log_path.parent() {
33        if !parent.as_os_str().is_empty() {
34            std::fs::create_dir_all(parent).map_err(|e| {
35                format!(
36                    "failed to write setup log {} (creating directory {}): {e}",
37                    log_path.display(),
38                    parent.display()
39                )
40            })?;
41        }
42    }
43    std::fs::write(log_path, content)
44        .map_err(|e| format!("failed to write setup log {}: {e}", log_path.display()))
45}
46
47fn tail_lines(text: &str, max_lines: usize) -> String {
48    let lines: Vec<&str> = text.lines().collect();
49    if lines.len() > max_lines {
50        lines[lines.len() - max_lines..].join("\n")
51    } else {
52        lines.join("\n")
53    }
54}
55
56fn format_stream_tails(stdout: &str, stderr: &str) -> String {
57    let mut sections = Vec::new();
58    if !stdout.is_empty() {
59        sections.push(format!("stdout:\n{}", tail_lines(stdout, 20)));
60    }
61    if !stderr.is_empty() {
62        sections.push(format!("stderr:\n{}", tail_lines(stderr, 20)));
63    }
64    sections.join("\n")
65}
66
67/// Runs `setup` with bash in `worktree`, outside the sandbox, writing its combined output to
68/// `log_path`. Every `env` entry and `BLYTE_MAIN_CHECKOUT=<main_checkout>` are exported first.
69/// Returns `Ok(())` when exit code is 0 and the log is written; otherwise returns `Err(message)`
70/// including the failure header, the last 20 lines of each non-empty stream under `stdout:` /
71/// `stderr:` labels, and a trailing `full log: <absolute path>` line (or the log write error
72/// naming the path if writing failed).
73pub fn run_setup(
74    setup: &str,
75    worktree: &Path,
76    main_checkout: &Path,
77    env: &BTreeMap<String, String>,
78    log_path: &Path,
79    timeout: Duration,
80) -> Result<(), String> {
81    run_setup_with_cwd(
82        setup,
83        worktree,
84        main_checkout,
85        env,
86        log_path,
87        timeout,
88        std::env::current_dir,
89    )
90}
91
92fn run_setup_with_cwd(
93    setup: &str,
94    worktree: &Path,
95    main_checkout: &Path,
96    env: &BTreeMap<String, String>,
97    log_path: &Path,
98    timeout: Duration,
99    get_cwd: impl FnOnce() -> std::io::Result<PathBuf>,
100) -> Result<(), String> {
101    let abs_log_path = absolute_log_path(log_path, get_cwd)?;
102
103    let mut script = String::new();
104    script.push_str(&format!(
105        "export BLYTE_MAIN_CHECKOUT={}\n",
106        quote(&main_checkout.to_string_lossy())
107    ));
108    for (k, v) in env {
109        script.push_str(&format!("export {k}={}\n", quote(v)));
110    }
111    script.push_str(setup);
112
113    let shell = blyte_agent::shell::LocalShell::new();
114    let res = shell.exec(&script, worktree, timeout);
115
116    let (header, tail, log_result) = match res {
117        Ok(output) => {
118            let combined = output.merged();
119            let log_result = write_setup_log(&abs_log_path, &combined);
120            if output.exit_code == 0 {
121                return log_result;
122            }
123            let is_timeout = output.exit_code == 124 && output.stderr.contains("killed by blyte");
124            let header = if is_timeout {
125                if timeout.as_secs() > 0 {
126                    format!("setup failed: timed out after {}s", timeout.as_secs())
127                } else {
128                    "setup failed: timed out".to_string()
129                }
130            } else {
131                format!("setup failed (exit {})", output.exit_code)
132            };
133            let tail = format_stream_tails(&output.stdout, &output.stderr);
134            (header, tail, log_result)
135        }
136        Err(e) => {
137            let log_result = write_setup_log(&abs_log_path, &format!("{e}\n"));
138            let header = format!("setup failed: {e}");
139            (header, String::new(), log_result)
140        }
141    };
142
143    let footer = match log_result {
144        Ok(()) => format!("full log: {}", abs_log_path.display()),
145        Err(log_err) => log_err,
146    };
147
148    let mut parts = vec![header];
149    if !tail.is_empty() {
150        parts.push(tail);
151    }
152    parts.push(footer);
153
154    Err(parts.join("\n"))
155}
156
157#[cfg(test)]
158mod tests {
159    use super::*;
160
161    #[test]
162    fn absolute_log_path_errors_when_current_dir_fails_for_relative_path() {
163        let rel = Path::new("relative/setup.log");
164        let err = absolute_log_path(rel, || {
165            Err(std::io::Error::new(
166                std::io::ErrorKind::NotFound,
167                "current directory removed",
168            ))
169        })
170        .expect_err("relative log path with failing current_dir must error");
171
172        assert!(
173            err.contains("relative/setup.log"),
174            "error must name the relative log path: {err}"
175        );
176        assert!(
177            err.contains("current working directory"),
178            "error must name the missing current working directory: {err}"
179        );
180        assert!(
181            err.contains("current directory removed"),
182            "error must include the cause: {err}"
183        );
184    }
185
186    #[test]
187    fn absolute_log_path_keeps_already_absolute_path_without_calling_cwd() {
188        let abs = Path::new("/tmp/already-abs/setup.log");
189        let resolved = absolute_log_path(abs, || {
190            Err(std::io::Error::new(
191                std::io::ErrorKind::NotFound,
192                "should not be called",
193            ))
194        })
195        .expect("absolute path should not need current_dir");
196        assert_eq!(resolved, abs);
197    }
198
199    #[test]
200    fn run_setup_errors_when_current_dir_fails_for_relative_log_path() {
201        let wt = tempfile::tempdir().unwrap();
202        let main = tempfile::tempdir().unwrap();
203        let env = BTreeMap::new();
204        let marker = wt.path().join("ran.txt");
205
206        let err = run_setup_with_cwd(
207            "echo ran > ran.txt",
208            wt.path(),
209            main.path(),
210            &env,
211            Path::new("nested/setup.log"),
212            SETUP_TIMEOUT,
213            || {
214                Err(std::io::Error::new(
215                    std::io::ErrorKind::NotFound,
216                    "cwd gone",
217                ))
218            },
219        )
220        .expect_err("run_setup with unresolvable relative log path must fail");
221
222        assert!(
223            err.contains("nested/setup.log"),
224            "error must name log path: {err}"
225        );
226        assert!(
227            err.contains("current working directory"),
228            "error must name missing current working directory: {err}"
229        );
230        assert!(err.contains("cwd gone"), "error must include cause: {err}");
231        assert!(
232            !marker.exists(),
233            "setup command must not run when log path cannot be resolved"
234        );
235    }
236}