use anyhow::Result;
use super::resolve_instance;
use crate::runtime::{backend, NAME_PREFIX};
use crate::state::State;
pub fn stop(name: Option<String>, all: bool) -> Result<()> {
let state = State::load()?;
if all {
let mut stopped = 0;
for (key, info) in &state.instances {
if let Some(why) = super::in_flight(key, info.progress.as_ref(), info.phase_view().as_ref()) {
eprintln!("skipping: {why}");
continue;
}
if backend().is_running(&info.container)? != Some(true) {
continue;
}
let services = service_containers(&info.project, &info.instance_id);
stop_containers(&info.container, &services);
println!("stopped {key}");
stopped += 1;
}
if stopped == 0 {
println!("nothing to stop");
}
return Ok(());
}
let name = name.expect("clap requires a name without --all");
let key = resolve_instance(&state, &name)?;
let info = state.instances.get(&key).expect("key came from state");
if let Some(why) = super::in_flight(&key, info.progress.as_ref(), info.phase_view().as_ref()) {
anyhow::bail!("{why}");
}
let services = service_containers(&info.project, &info.instance_id);
stop_containers(&info.container, &services);
println!("stopped {key}");
Ok(())
}
pub(crate) fn service_containers(project: &str, instance_id: &str) -> Vec<String> {
if project.is_empty() {
return Vec::new();
}
match backend().list(true, NAME_PREFIX) {
Ok(rows) => rows
.into_iter()
.filter(|r| {
r.label("devsandbox.project") == Some(project)
&& r.label("devsandbox.instance") == Some(instance_id)
})
.map(|r| r.name)
.collect(),
Err(_) => Vec::new(),
}
}
pub(crate) fn stop_containers(container: &str, services: &[String]) {
let mut targets: Vec<&str> = Vec::with_capacity(services.len() + 1);
targets.push(container);
targets.extend(services.iter().map(String::as_str));
for target in targets {
let _ = backend().run_inherit(&["stop", target]);
}
}