use serde_json::{Map, Value};
use crate::model::{ALL, Group, InventoryData};
pub const INTERNAL_STATIC_VARS: &[&str] = &[
"ansible_async_path",
"ansible_collection_name",
"ansible_config_file",
"ansible_dependent_role_names",
"ansible_diff_mode",
"ansible_facts",
"ansible_forks",
"ansible_inventory_sources",
"ansible_limit",
"ansible_play_batch",
"ansible_play_hosts",
"ansible_play_hosts_all",
"ansible_play_role_names",
"ansible_playbook_python",
"ansible_role_name",
"ansible_role_names",
"ansible_run_tags",
"ansible_skip_tags",
"ansible_verbosity",
"ansible_version",
"group_names",
"groups",
"hostvars",
"inventory_dir",
"inventory_file",
"inventory_hostname",
"inventory_hostname_short",
"omit",
"play_hosts",
"playbook_dir",
"role_name",
"role_names",
"role_path",
"role_uuid",
];
pub fn combine(dst: &mut Map<String, Value>, src: &Map<String, Value>) {
for (k, v) in src {
dst.insert(k.clone(), v.clone());
}
}
fn sort_key(g: &Group) -> (u32, i64, &str) {
(g.depth, g.priority, g.name.as_str())
}
fn host_groups_sorted<'a>(inv: &'a InventoryData, host: &str) -> Vec<&'a Group> {
let mut groups: Vec<&Group> = inv
.host_groups(host)
.into_iter()
.filter(|g| g != ALL)
.filter_map(|g| inv.groups.get(&g))
.collect();
groups.sort_by(|a, b| sort_key(a).cmp(&sort_key(b)));
groups
}
pub fn resolve_host_vars(inv: &InventoryData, host: &str) -> Map<String, Value> {
let mut result = Map::new();
if let Some(all) = inv.groups.get(ALL) {
combine(&mut result, &all.vars);
combine(&mut result, &all.file_vars);
}
let groups = host_groups_sorted(inv, host);
for g in &groups {
combine(&mut result, &g.vars);
}
for g in &groups {
combine(&mut result, &g.file_vars);
}
if let Some(h) = inv.hosts.get(host) {
combine(&mut result, &h.vars);
combine(&mut result, &h.file_vars);
}
result
}
pub fn resolve_host_inline_vars(inv: &InventoryData, host: &str) -> Map<String, Value> {
let mut result = Map::new();
if let Some(all) = inv.groups.get(ALL) {
combine(&mut result, &all.vars);
}
for g in host_groups_sorted(inv, host) {
combine(&mut result, &g.vars);
}
if let Some(h) = inv.hosts.get(host) {
combine(&mut result, &h.vars);
}
result
}
pub fn remove_internal(vars: &mut Map<String, Value>) {
for k in INTERNAL_STATIC_VARS {
vars.remove(*k);
}
}