use std::borrow::Cow; use std::path::Path; use std::process::Command; use indexmap::IndexMap; use serde_json::Value as JsonValue; use crate::config::{CommandSpec, MigrationSpec, TaskSpec}; use crate::error::{Result, RoneoError}; use crate::renderer::TemplateRenderer; use crate::version::Pep440Version; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum MigrationStage { Before, After, } impl MigrationStage { pub fn as_str(self) -> &'static str { match self { Self::Before => "before", Self::After => "after", } } } /// Parameters controlling a migration stage execution (`before` or `after` update). pub struct MigrationRun<'a> { pub version_from: &'a str, pub version_to: &'a str, pub stage: MigrationStage, pub dst_path: &'a Path, pub renderer: &'a TemplateRenderer, pub ctx: &'a IndexMap, pub pretend: bool, } /// Execute a list of post-copy/post-update tasks. pub fn run_tasks( tasks: &[TaskSpec], dst_path: &Path, renderer: &TemplateRenderer, ctx: &IndexMap, extra_env: &[(&str, &str)], pretend: bool, mut on_run: F, ) -> Result<()> where F: FnMut(&str), { if tasks.is_empty() { return Ok(()); } let task_ctx: Cow<'_, IndexMap> = if ctx.contains_key("_stage") { Cow::Borrowed(ctx) } else { let mut cloned = ctx.clone(); cloned.insert("_stage".into(), JsonValue::String("task".into())); Cow::Owned(cloned) }; let stage_env = task_ctx .get("_stage") .and_then(JsonValue::as_str) .unwrap_or("task"); let operation_env = task_ctx .get("_copier_operation") .and_then(JsonValue::as_str) .unwrap_or(""); for (idx, task) in tasks.iter().enumerate() { if let Some(when_expr) = &task.when && !renderer.eval_condition_str(when_expr, &task_ctx, &format!("task[{idx}].when"))? { continue; } let work_dir = match &task.working_directory { Some(dir_tpl) => { let dir_str = renderer.render_str( dir_tpl, &task_ctx, &format!("task[{idx}].working_directory"), )?; let candidate = Path::new(&dir_str); if candidate.is_absolute() { candidate.to_path_buf() } else { dst_path.join(candidate) } } None => dst_path.to_path_buf(), }; let (display_cmd, mut cmd) = match &task.command { CommandSpec::Shell(script) => { let expanded = renderer.render_str(script, &task_ctx, &format!("task[{idx}]"))?; let cmd = shell_command(&expanded); (expanded, cmd) } CommandSpec::Args(args) => { let evaluated = render_args(args, renderer, &task_ctx, idx)?; let display = evaluated.join(" "); let Some((prog, rest)) = evaluated.split_first() else { continue; }; let mut cmd = Command::new(prog); cmd.args(rest); (display, cmd) } }; on_run(&display_cmd); if pretend { continue; } cmd.current_dir(&work_dir).env("STAGE", stage_env); if !operation_env.is_empty() { cmd.env("COPIER_OPERATION", operation_env); } for (k, v) in extra_env { cmd.env(k, v); } for (ek, ev_tpl) in &task.extra_env { let rendered_val = renderer.render_str(ev_tpl, &task_ctx, &format!("task[{idx}].extra_env.{ek}"))?; cmd.env(ek, rendered_val); } let output = cmd.output().map_err(|e| RoneoError::TaskFailed { command: display_cmd.clone(), status: None, stderr: e.to_string(), })?; if !output.status.success() { return Err(RoneoError::TaskFailed { command: display_cmd, status: output.status.code(), stderr: String::from_utf8_lossy(&output.stderr).trim().to_string(), }); } } Ok(()) } /// Run applicable `_migrations` between `version_from` and `version_to` for the given stage. pub fn run_migrations( migrations: &[MigrationSpec], run: &MigrationRun<'_>, mut on_run: F, ) -> Result<()> where F: FnMut(&str), { let from_ver = Pep440Version::parse(run.version_from); let to_ver = Pep440Version::parse(run.version_to); let mut applicable: Vec<(&MigrationSpec, Option)> = migrations .iter() .filter_map(|m| match &m.version { None => Some((m, None)), Some(ver_str) => { let v = Pep440Version::parse(ver_str)?; let (Some(from), Some(to)) = (&from_ver, &to_ver) else { return None; }; (to > from && v > *from && v <= *to).then_some((m, Some(v))) } }) .collect(); if applicable.is_empty() { return Ok(()); } applicable.sort_by(|a, b| a.1.cmp(&b.1)); let mut stage_ctx = run.ctx.clone(); stage_ctx.insert( "_stage".into(), JsonValue::String(run.stage.as_str().into()), ); for (migration, _) in applicable { if let Some(when_expr) = &migration.when && !run .renderer .eval_condition_str(when_expr, &stage_ctx, "migration.when")? { continue; } let current_ver = migration.version.as_deref().unwrap_or(""); let env = [ ("VERSION_FROM", run.version_from), ("VERSION_TO", run.version_to), ("VERSION_CURRENT", current_ver), ("STAGE", run.stage.as_str()), ]; let stage_tasks = match run.stage { MigrationStage::Before => &migration.before, MigrationStage::After => &migration.after, }; run_tasks( stage_tasks, run.dst_path, run.renderer, &stage_ctx, &env, run.pretend, &mut on_run, )?; if let Some(cmd) = &migration.command { let single = [TaskSpec { command: cmd.clone(), when: None, working_directory: None, extra_env: IndexMap::new(), }]; run_tasks( &single, run.dst_path, run.renderer, &stage_ctx, &env, run.pretend, &mut on_run, )?; } } Ok(()) } fn render_args( args: &[String], renderer: &TemplateRenderer, ctx: &IndexMap, idx: usize, ) -> Result> { args.iter() .enumerate() .map(|(j, a)| renderer.render_str(a, ctx, &format!("task[{idx}][{j}]"))) .collect() } #[cfg(unix)] fn shell_command(script: &str) -> Command { let mut cmd = Command::new("sh"); cmd.arg("-c").arg(script); cmd } #[cfg(windows)] fn shell_command(script: &str) -> Command { let mut cmd = Command::new("cmd"); cmd.arg("/C").arg(script); cmd }