use std::collections::BTreeSet;
use isoloom_manifest::{Argv, GoneError, HostArgv, HostOs, Run, Step, Template};
use serde_json::Value;
use super::state::array;
use crate::Result;
use crate::events::WarningCode;
use crate::executor::Cx;
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Gone {
pub(crate) address: String,
pub(crate) text: String,
}
pub(super) fn in_state(state: &Value, errors: &[GoneError]) -> Vec<Gone> {
let mut out = Vec::new();
for resource in array(state, "resources") {
if resource.get("mode").and_then(Value::as_str) != Some("managed") {
continue;
}
let kind = resource.get("type").and_then(Value::as_str);
for error in errors.iter().filter(|e| Some(e.resource.as_str()) == kind) {
for instance in array(resource, "instances") {
let attributes = instance.get("attributes");
let text = error.error.fill(|name| attributes.and_then(|a| a.get(name)).and_then(super::state::scalar));
if let (Some(text), Some(address)) = (text, address(resource, instance)) {
out.push(Gone { address, text });
}
}
}
}
out
}
fn address(resource: &Value, instance: &Value) -> Option<String> {
let field = |key| resource.get(key).and_then(Value::as_str);
let module = field("module").map(|m| format!("{m}.")).unwrap_or_default();
let key = match instance.get("index_key") {
None | Some(Value::Null) => String::new(),
Some(n @ Value::Number(_)) => format!("[{n}]"),
Some(s @ Value::String(_)) => format!("[{s}]"),
Some(_) => return None,
};
Some(format!("{module}{}.{}{key}", field("type")?, field("name")?))
}
pub(super) async fn forget(cx: &Cx<'_>, list: &str, step: &Step, held: Vec<Gone>, seen: &BTreeSet<String>) -> Result<bool> {
let found: Vec<Gone> = held.into_iter().filter(|g| seen.contains(&g.text)).collect();
let Some(rm) = state_rm(step, cx.scope.host, &found) else {
return Ok(false);
};
for g in &found {
let message = format!("`{}` is already gone ({}): dropped from the state, then destroyed again", g.address, g.text);
cx.events.warning(WarningCode::AlreadyGone, &message);
}
crate::executor::run_argv(cx, list, &rm, &mut |_| {}).await?;
Ok(true)
}
fn state_rm(step: &Step, host: HostOs, gone: &[Gone]) -> Option<Step> {
let Run::Argv(command) = &step.run else { return None };
let chosen = crate::executor::plan::for_host(command, host)?;
let (at, subcommand) = super::argv::subcommand(chosen)?;
if gone.is_empty() || subcommand != "destroy" {
return None;
}
let mut args: Vec<Template> = chosen.args().iter().take(at).cloned().collect();
args.extend(["state", "rm"].map(Template::text));
args.extend(gone.iter().map(|g| Template::text(&g.address)));
let mut rm = step.clone();
rm.run = Run::Argv(HostArgv::Every(Argv::new(chosen.program().clone(), args)));
rm.stdin = None;
rm.verdict = None;
Some(rm)
}
#[cfg(test)]
mod tests;