71 lines
1.9 KiB
Rust
71 lines
1.9 KiB
Rust
use std::{
|
|
path::Path,
|
|
process::{Command, ExitStatus},
|
|
};
|
|
|
|
use anyhow::{bail, Context, Result};
|
|
use directories::BaseDirs;
|
|
|
|
fn is_container_running(container_name: &str) -> Result<bool> {
|
|
let output = Command::new("docker")
|
|
.args(["ps", "--format", "{{.Names}}"])
|
|
.output()?;
|
|
|
|
let output_str = String::from_utf8_lossy(&output.stdout);
|
|
let running: bool = output_str.lines().any(|line| line.trim() == container_name);
|
|
|
|
Ok(running)
|
|
}
|
|
|
|
pub fn start_docker_compose(
|
|
service_name: &str,
|
|
container_path: &str,
|
|
start: bool,
|
|
) -> Result<()> {
|
|
let base_dir: BaseDirs = BaseDirs::new().context("Could not determine home directory")?;
|
|
let absolute = base_dir.home_dir().join(container_path);
|
|
let compose_path = Path::new(&absolute);
|
|
println!("{}", compose_path.to_str().context("Invalid path")?);
|
|
|
|
let running: bool = is_container_running(service_name)?;
|
|
|
|
if running && start {
|
|
println!("Container running already.");
|
|
return Ok(());
|
|
}
|
|
|
|
if start && compose_path.exists() {
|
|
let status: ExitStatus = Command::new("docker")
|
|
.current_dir(compose_path)
|
|
.args(["compose", "up", "-d"])
|
|
.status()?;
|
|
|
|
if status.success() {
|
|
println!(
|
|
"Docker Compose service '{}' started successfully.",
|
|
service_name
|
|
);
|
|
} else {
|
|
bail!("Failed to start Docker Compose service '{}'.", service_name);
|
|
}
|
|
}
|
|
|
|
if !start && compose_path.exists() {
|
|
let status: ExitStatus = Command::new("docker")
|
|
.current_dir(compose_path)
|
|
.args(["compose", "down"])
|
|
.status()?;
|
|
|
|
if status.success() {
|
|
println!(
|
|
"Docker Compose service '{}' stopped successfully.",
|
|
service_name
|
|
);
|
|
} else {
|
|
bail!("Failed to stop Docker Compose service '{}'.", service_name);
|
|
}
|
|
}
|
|
|
|
Ok(())
|
|
}
|