diff --git a/Cargo.lock b/Cargo.lock index 871e5ad9..35f4229c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -120,6 +120,7 @@ dependencies = [ "serde_yaml", "tempfile", "toml 1.0.3+spec-1.1.0", + "wait-timeout", ] [[package]] diff --git a/crates/bough-cli/Cargo.toml b/crates/bough-cli/Cargo.toml index 99b39bfc..5c81feb5 100644 --- a/crates/bough-cli/Cargo.toml +++ b/crates/bough-cli/Cargo.toml @@ -19,6 +19,7 @@ toml = "1.0.3" serde_yaml = "0.9.34" serde-value = "0.7.0" glob = "0.3" +wait-timeout = "0.2" [dev-dependencies] assert_cmd = "2.1.2" diff --git a/crates/bough-cli/src/main.rs b/crates/bough-cli/src/main.rs index 387dc2d4..04819d4c 100644 --- a/crates/bough-cli/src/main.rs +++ b/crates/bough-cli/src/main.rs @@ -1,4 +1,5 @@ mod config; +mod phase_runner; mod render; mod steps; @@ -47,6 +48,10 @@ enum Command { enum WorkspaceAction { Make, List, + Init { + #[arg()] + path: PathBuf, + }, Drop { #[arg()] name: String, @@ -98,6 +103,18 @@ fn main() { let no_color = !std::io::IsTerminal::is_terminal(&std::io::stdout()); result.render(&cli.output_style, no_color, 0); } + WorkspaceAction::Init { path } => { + let cfg = config::load(&cli).unwrap_or_else(|e| { + eprintln!("{e}"); + std::process::exit(1); + }); + let result = steps::init_workspace::run(&cfg, &path).unwrap_or_else(|e| { + eprintln!("{e}"); + std::process::exit(1); + }); + let no_color = !std::io::IsTerminal::is_terminal(&std::io::stdout()); + result.render(&cli.output_style, no_color, 0); + } WorkspaceAction::Drop { name } => { let cfg = config::load(&cli).unwrap_or_else(|e| { eprintln!("{e}"); diff --git a/crates/bough-cli/src/phase_runner.rs b/crates/bough-cli/src/phase_runner.rs new file mode 100644 index 00000000..9070c4cb --- /dev/null +++ b/crates/bough-cli/src/phase_runner.rs @@ -0,0 +1,158 @@ +use std::collections::HashMap; +use std::io::Read; +use std::path::Path; +use std::process::{Command, Stdio}; +use std::time::Duration; +use wait_timeout::ChildExt; + +#[derive(Debug)] +pub enum Error { + Command { + index: usize, + cmd: String, + source: std::io::Error, + }, + CommandFailed { + index: usize, + cmd: String, + code: i32, + #[allow(dead_code)] + stdout: String, + }, + Timeout { + index: usize, + cmd: String, + #[allow(dead_code)] + stdout: String, + }, +} + +impl std::fmt::Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Error::Command { index, cmd, source } => { + write!(f, "command [{index}] `{cmd}` failed to start: {source}") + } + Error::CommandFailed { index, cmd, code, .. } => { + write!(f, "command [{index}] `{cmd}` exited with code {code}") + } + Error::Timeout { index, cmd, .. } => { + write!(f, "command [{index}] `{cmd}` timed out") + } + } + } +} + +impl std::error::Error for Error {} + +pub struct PhaseRunner<'a> { + commands: Vec, + pwd: &'a Path, + env: HashMap, + timeout: Option, +} + +#[derive(Debug, Default)] +pub struct PhaseOutput { + pub stdout: String, +} + +impl<'a> PhaseRunner<'a> { + pub fn new( + commands: Vec, + pwd: &'a Path, + env: HashMap, + timeout_secs: Option, + ) -> Self { + Self { + commands, + pwd, + env, + timeout: timeout_secs.map(Duration::from_secs), + } + } + + pub fn run(&self) -> Result { + let mut combined_stdout = String::new(); + for (i, cmd) in self.commands.iter().enumerate() { + let stdout = self.run_one(i, cmd)?; + combined_stdout.push_str(&stdout); + } + Ok(PhaseOutput { + stdout: combined_stdout, + }) + } + + fn run_one(&self, index: usize, cmd: &str) -> Result { + let mut child = Command::new("sh") + .arg("-c") + .arg(cmd) + .current_dir(&self.pwd) + .envs(&self.env) + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()) + .spawn() + .map_err(|e| Error::Command { + index, + cmd: cmd.to_string(), + source: e, + })?; + + let read_stdout = |child: &mut std::process::Child| -> String { + let mut buf = String::new(); + if let Some(mut stdout) = child.stdout.take() { + let _ = stdout.read_to_string(&mut buf); + } + buf + }; + + match self.timeout { + Some(duration) => { + let status = child + .wait_timeout(duration) + .map_err(|e| Error::Command { + index, + cmd: cmd.to_string(), + source: e, + })?; + let stdout = read_stdout(&mut child); + match status { + Some(exit) if exit.success() => Ok(stdout), + Some(exit) => Err(Error::CommandFailed { + index, + cmd: cmd.to_string(), + code: exit.code().unwrap_or(-1), + stdout, + }), + None => { + let _ = child.kill(); + let _ = child.wait(); + Err(Error::Timeout { + index, + cmd: cmd.to_string(), + stdout, + }) + } + } + } + None => { + let stdout = read_stdout(&mut child); + let status = child.wait().map_err(|e| Error::Command { + index, + cmd: cmd.to_string(), + source: e, + })?; + if status.success() { + Ok(stdout) + } else { + Err(Error::CommandFailed { + index, + cmd: cmd.to_string(), + code: status.code().unwrap_or(-1), + stdout, + }) + } + } + } + } +} diff --git a/crates/bough-cli/src/steps/init_workspace.rs b/crates/bough-cli/src/steps/init_workspace.rs new file mode 100644 index 00000000..17a2b046 --- /dev/null +++ b/crates/bough-cli/src/steps/init_workspace.rs @@ -0,0 +1,98 @@ +use bough_core::config::Config; +use serde::Serialize; +use std::path::{Path, PathBuf}; + +use crate::phase_runner::PhaseRunner; +use crate::render::{Render, color}; + +#[derive(Debug)] +pub enum Error { + NoActiveRunner, + NoInitPhase, + WorkspaceNotFound(PathBuf), + Phase(crate::phase_runner::Error), +} + +impl std::fmt::Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Error::NoActiveRunner => write!(f, "no active runner configured"), + Error::NoInitPhase => write!(f, "no init phase configured for runner"), + Error::WorkspaceNotFound(p) => write!(f, "workspace not found: {}", p.display()), + Error::Phase(e) => write!(f, "init phase failed: {e}"), + } + } +} + +impl std::error::Error for Error {} + +#[derive(Debug, Serialize)] +pub struct InitWorkspace { + pub workspace: PathBuf, + pub stdout: String, +} + +pub fn run(config: &Config, workspace: &Path) -> Result { + let runner_name = config.resolved_runner_name().ok_or(Error::NoActiveRunner)?; + + if !config.runner_has_init(runner_name) { + return Err(Error::NoInitPhase); + } + + if !workspace.exists() { + return Err(Error::WorkspaceNotFound(workspace.to_path_buf())); + } + + let commands = config + .runner_init_commands(runner_name) + .ok_or(Error::NoInitPhase)?; + let runner_pwd = config.runner_pwd(runner_name).unwrap_or("."); + let pwd = workspace.join(runner_pwd); + let env = config.runner_init_env(runner_name); + let timeout = config.runner_init_timeout_absolute(runner_name); + + let output = PhaseRunner::new(commands, &pwd, env, timeout) + .run() + .map_err(Error::Phase)?; + + Ok(InitWorkspace { + workspace: workspace.to_path_buf(), + stdout: output.stdout, + }) +} + +impl Render for InitWorkspace { + fn render_value(&self) -> serde_value::Value { + serde_value::to_value(self).expect("failed to serialize") + } + + fn render_terse(&self) -> String { + format!( + "initialized workspace {}\n", + color("\x1b[1m", &self.workspace.display().to_string()), + ) + } + + fn render_verbose(&self) -> String { + let mut out = format!( + "initialized workspace {}\n", + color("\x1b[1m", &self.workspace.display().to_string()), + ); + if !self.stdout.is_empty() { + out.push_str(&color("\x1b[2m", &self.stdout)); + } + out + } + + fn render_markdown(&self, depth: u8) -> String { + let heading = "#".repeat((depth + 1).min(6) as usize); + let mut out = format!( + "{heading} Init Workspace\n\n- **Path:** `{}`\n", + self.workspace.display(), + ); + if !self.stdout.is_empty() { + out.push_str(&format!("\n```\n{}\n```\n", self.stdout.trim())); + } + out + } +} diff --git a/crates/bough-cli/src/steps/make_workspace.rs b/crates/bough-cli/src/steps/make_workspace.rs index a2f52d1a..d27ab3c4 100644 --- a/crates/bough-cli/src/steps/make_workspace.rs +++ b/crates/bough-cli/src/steps/make_workspace.rs @@ -33,23 +33,22 @@ pub struct MakeWorkspace { pub path: PathBuf, pub vcs: VcsConfig, pub name: Option, + pub stdout: String, } -fn run_cmd(cmd: &str, args: &[&str], cwd: &Path) -> Result<(), Error> { +fn run_cmd(cmd: &str, args: &[&str], cwd: &Path) -> Result { let output = Command::new(cmd) .args(args) .current_dir(cwd) - .stdout(std::process::Stdio::null()) - .stderr(std::process::Stdio::null()) - .status() + .output() .map_err(|e| Error::Command(format!("{cmd} {}", args.join(" ")), e))?; - if !output.success() { + if !output.status.success() { return Err(Error::CommandFailed( format!("{cmd} {}", args.join(" ")), - output.code().unwrap_or(-1), + output.status.code().unwrap_or(-1), )); } - Ok(()) + Ok(String::from_utf8_lossy(&output.stdout).into_owned()) } fn generate_name() -> String { @@ -68,31 +67,31 @@ pub fn run(config: &Config) -> Result { std::fs::create_dir_all(&base_dir).map_err(Error::CreateDir)?; - let (name, ws_dir) = match &vcs { + let (name, ws_dir, stdout) = match &vcs { VcsConfig::Jj { .. } => { let name = generate_name(); let ws_dir = base_dir.join(&name); - run_cmd( + let stdout = run_cmd( "jj", &["workspace", "add", "--name", &name, &ws_dir.to_string_lossy()], Path::new(runner_pwd), )?; - (Some(name), ws_dir) + (Some(name), ws_dir, stdout) } VcsConfig::Git { .. } => { let name = generate_name(); let ws_dir = base_dir.join(&name); - run_cmd( + let stdout = run_cmd( "git", &["worktree", "add", "-b", &name, &ws_dir.to_string_lossy()], Path::new(runner_pwd), )?; - (Some(name), ws_dir) + (Some(name), ws_dir, stdout) } VcsConfig::None => { let name = generate_name(); let ws_dir = base_dir.join(&name); - run_cmd( + let stdout = run_cmd( "cp", &["-a", runner_pwd, &ws_dir.to_string_lossy()], Path::new(runner_pwd), @@ -102,7 +101,7 @@ pub fn run(config: &Config) -> Result { Error::CommandFailed(cmd, code) => Error::Copy(cmd, std::io::Error::other(format!("exit code {code}"))), other => other, })?; - (None, ws_dir) + (None, ws_dir, stdout) } VcsConfig::Mercurial => { todo!("mercurial workspace support") @@ -113,6 +112,7 @@ pub fn run(config: &Config) -> Result { path: ws_dir, vcs, name, + stdout, }) } @@ -143,6 +143,9 @@ impl Render for MakeWorkspace { if let Some(name) = &self.name { out.push_str(&format!(" name: {}\n", color("\x1b[33m", name))); } + if !self.stdout.is_empty() { + out.push_str(&color("\x1b[2m", &self.stdout)); + } out } @@ -156,6 +159,9 @@ impl Render for MakeWorkspace { if let Some(name) = &self.name { out.push_str(&format!("- **Name:** `{name}`\n")); } + if !self.stdout.is_empty() { + out.push_str(&format!("\n```\n{}\n```\n", self.stdout.trim())); + } out } } diff --git a/crates/bough-cli/src/steps/mod.rs b/crates/bough-cli/src/steps/mod.rs index 1541c8b7..2a8c1a3e 100644 --- a/crates/bough-cli/src/steps/mod.rs +++ b/crates/bough-cli/src/steps/mod.rs @@ -2,5 +2,6 @@ pub mod drop_workspace; pub mod get_all_test_ids; pub mod get_mutations; pub mod get_src_files; +pub mod init_workspace; pub mod list_workspaces; pub mod make_workspace; diff --git a/crates/bough-core/src/config/mod.rs b/crates/bough-core/src/config/mod.rs index cb2845c4..a6a9b8b4 100644 --- a/crates/bough-core/src/config/mod.rs +++ b/crates/bough-core/src/config/mod.rs @@ -342,6 +342,21 @@ impl Config { .map(|p| p.pwd.as_str()) } + pub fn runner_init_timeout_absolute(&self, runner: &str) -> Option { + self.runners + .get(runner) + .and_then(|r| r.init.as_ref()) + .and_then(|p| p.timeout.absolute) + } + + pub fn runner_init_env(&self, runner: &str) -> HashMap { + self.runners + .get(runner) + .and_then(|r| r.init.as_ref()) + .map(|p| p.env.clone()) + .unwrap_or_default() + } + pub fn runner_has_init(&self, runner: &str) -> bool { self.runners.get(runner).is_some_and(|r| r.init.is_some()) } @@ -364,6 +379,21 @@ impl Config { .map(|p| p.pwd.as_str()) } + pub fn runner_reset_timeout_absolute(&self, runner: &str) -> Option { + self.runners + .get(runner) + .and_then(|r| r.reset.as_ref()) + .and_then(|p| p.timeout.absolute) + } + + pub fn runner_reset_env(&self, runner: &str) -> HashMap { + self.runners + .get(runner) + .and_then(|r| r.reset.as_ref()) + .map(|p| p.env.clone()) + .unwrap_or_default() + } + pub fn runner_test_commands(&self, runner: &str) -> Vec { self.runners .get(runner) @@ -457,15 +487,7 @@ impl Config { resolve(&mut self.dirs.state); resolve(&mut self.dirs.logs); - for runner in self.runners.values_mut() { - resolve(&mut runner.pwd); - if let Some(phase) = &mut runner.init { - resolve(&mut phase.pwd); - } - if let Some(phase) = &mut runner.reset { - resolve(&mut phase.pwd); - } - resolve(&mut runner.test.pwd); + for _runner in self.runners.values_mut() { } } } diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 00000000..e833f800 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,6 @@ +{ + "name": "pollard", + "lockfileVersion": 3, + "requires": true, + "packages": {} +}