1use std::collections::BTreeMap;
4use std::path::Path;
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
15pub fn run_setup(
21 setup: &str,
22 worktree: &Path,
23 main_checkout: &Path,
24 env: &BTreeMap<String, String>,
25 log_path: &Path,
26 timeout: Duration,
27) -> Result<(), String> {
28 let mut script = String::new();
29 script.push_str(&format!(
30 "export BLYTE_MAIN_CHECKOUT={}\n",
31 quote(&main_checkout.to_string_lossy())
32 ));
33 for (k, v) in env {
34 script.push_str(&format!("export {k}={}\n", quote(v)));
35 }
36 script.push_str(setup);
37
38 if let Some(parent) = log_path.parent() {
39 let _ = std::fs::create_dir_all(parent);
40 }
41
42 let shell = blyte_agent::shell::LocalShell::new();
43 let res = shell.exec(&script, worktree, timeout);
44
45 let (header, combined) = match res {
46 Ok(output) => {
47 let combined = output.merged();
48 let _ = std::fs::write(log_path, &combined);
49 if output.exit_code == 0 {
50 return Ok(());
51 }
52 let is_timeout = output.exit_code == 124 && output.stderr.contains("killed by blyte");
53 let header = if is_timeout {
54 if timeout.as_secs() > 0 {
55 format!("setup failed: timed out after {}s", timeout.as_secs())
56 } else {
57 "setup failed: timed out".to_string()
58 }
59 } else {
60 format!("setup failed (exit {})", output.exit_code)
61 };
62 (header, combined)
63 }
64 Err(e) => {
65 let _ = std::fs::write(log_path, format!("{e}\n"));
66 let header = format!("setup failed: {e}");
67 (header, String::new())
68 }
69 };
70
71 let lines: Vec<&str> = combined.lines().collect();
72 let tail = if lines.len() > 20 {
73 lines[lines.len() - 20..].join("\n")
74 } else {
75 lines.join("\n")
76 };
77
78 let msg = if tail.is_empty() {
79 header
80 } else {
81 format!("{header}\n{tail}")
82 };
83
84 Err(msg)
85}