|
| 1 | +use anyhow::{bail, Result}; |
| 2 | +use serde_json::Value; |
| 3 | +use std::path::PathBuf; |
| 4 | +use std::process::Command; |
| 5 | +use std::thread; |
| 6 | +use std::time::Duration; |
| 7 | + |
| 8 | +pub fn start(config: Value) -> Result<()> { |
| 9 | + let mut command = compose_command(); |
| 10 | + command.args(["up", "-d"]); |
| 11 | + |
| 12 | + apply_env_vars(&mut command, &config); |
| 13 | + |
| 14 | + let status = command.status()?; |
| 15 | + if status.success() { |
| 16 | + thread::sleep(Duration::from_secs(20)); |
| 17 | + return Ok(()); |
| 18 | + } else { |
| 19 | + bail!("failed to execute: {}", render_command(&mut command)); |
| 20 | + } |
| 21 | +} |
| 22 | + |
| 23 | +pub fn stop(config: Value) -> Result<()> { |
| 24 | + let mut command = compose_command(); |
| 25 | + command.args(["down", "-t", "0"]); |
| 26 | + |
| 27 | + apply_env_vars(&mut command, &config); |
| 28 | + |
| 29 | + let status = command.status()?; |
| 30 | + if status.success() { |
| 31 | + return Ok(()); |
| 32 | + } else { |
| 33 | + bail!("failed to execute: {}", render_command(&mut command)); |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +fn compose_command() -> Command { |
| 38 | + let path = PathBuf::from_iter(["data", "docker-compose.yml"].iter()); |
| 39 | + let compose_file = match dunce::canonicalize(&path) { |
| 40 | + Ok(p) => p.display().to_string(), |
| 41 | + Err(_) => path.display().to_string(), |
| 42 | + }; |
| 43 | + |
| 44 | + let mut command = Command::new("docker"); |
| 45 | + command.args(["compose", "-f", &compose_file]); |
| 46 | + command |
| 47 | +} |
| 48 | + |
| 49 | +fn apply_env_vars(command: &mut Command, config: &Value) { |
| 50 | + if let Some(version) = config.get("version") { |
| 51 | + command.env("REDIS_VERSION", version.as_str().unwrap()); |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +fn render_command(command: &mut Command) -> String { |
| 56 | + format!( |
| 57 | + "{} {}", |
| 58 | + command.get_program().to_str().unwrap(), |
| 59 | + Vec::from_iter(command.get_args().map(|arg| arg.to_str().unwrap())).join(" ") |
| 60 | + ) |
| 61 | +} |
0 commit comments