use std::collections::HashSet;
use std::path::PathBuf;
use anyhow::{Context, bail};
use clap::{ArgGroup, Parser};
use crate::enabled::EnabledKinds;
use crate::output::{GroupPruning, build_host, build_list, build_toml, build_yaml};
use crate::parse::load_sources;
use crate::serialize::{to_json, to_toml, to_yaml};
#[derive(Parser, Debug)]
#[command(
name = "fleets",
version,
about = "A fast, mostly ansible-inventory-compatible inventory tool",
group(
ArgGroup::new("action")
.required(true)
.multiple(false)
.args(["list", "host"])
)
)]
pub struct Args {
#[arg(long)]
pub list: bool,
#[arg(long, value_name = "HOST")]
pub host: Option<String>,
#[arg(short = 'i', long = "inventory", value_name = "PATH")]
pub inventory: Vec<PathBuf>,
#[arg(short = 'l', long = "limit", value_name = "PATTERN")]
pub limit: Option<String>,
#[arg(short = 'y', long, conflicts_with = "toml")]
pub yaml: bool,
#[arg(long, conflicts_with = "yaml")]
pub toml: bool,
#[arg(long)]
pub export: bool,
#[arg(long)]
pub strict_compatibility: bool,
}
pub fn run(args: &Args) -> anyhow::Result<String> {
let sources = resolve_sources(args)?;
match (args.list, args.host.is_some()) {
(true, true) => bail!("--list and --host are mutually exclusive"),
(false, false) => bail!("one of --list or --host is required"),
_ => {}
}
if args.yaml && args.toml {
bail!("--yaml and --toml are mutually exclusive");
}
let pruning = if args.list && strict_compatibility(args)? {
GroupPruning::AnsibleCompatible
} else {
GroupPruning::GraphAware
};
let enabled = EnabledKinds::from_env();
let inv = load_sources(&sources, enabled).context("loading inventory")?;
let available: HashSet<String> = match &args.limit {
Some(limit) => crate::pattern::select_hosts(&inv, limit),
None => inv.hosts.keys().cloned().collect(),
};
if let Some(host) = &args.host {
let value = build_host(&inv, host, args.export)
.with_context(|| format!("host '{host}' not found in inventory"))?;
return render(&value, args);
}
let value = if args.yaml {
build_yaml(&inv, &available, args.export, pruning)
} else if args.toml {
build_toml(&inv, &available, args.export, pruning)
} else {
build_list(&inv, &available, args.export, pruning)
};
render(&value, args)
}
fn strict_compatibility(args: &Args) -> anyhow::Result<bool> {
let from_env = match std::env::var("FLEETS_STRICT_COMPATIBILITY") {
Ok(value) => match value.trim().to_ascii_lowercase().as_str() {
"true" | "1" => true,
"false" | "0" => false,
_ => bail!(
"invalid FLEETS_STRICT_COMPATIBILITY value {value:?} (expected true, false, 1, or 0)"
),
},
Err(std::env::VarError::NotPresent) => false,
Err(std::env::VarError::NotUnicode(_)) => {
bail!("FLEETS_STRICT_COMPATIBILITY must be valid UTF-8")
}
};
Ok(args.strict_compatibility || from_env)
}
fn resolve_sources(args: &Args) -> anyhow::Result<Vec<PathBuf>> {
if !args.inventory.is_empty() {
return Ok(args.inventory.clone());
}
if let Some(val) = std::env::var_os("ANSIBLE_INVENTORY") {
let sources: Vec<PathBuf> = val
.to_string_lossy()
.split(',')
.map(str::trim)
.filter(|s| !s.is_empty())
.map(PathBuf::from)
.collect();
if !sources.is_empty() {
return Ok(sources);
}
}
bail!("no inventory source given (use -i/--inventory or set ANSIBLE_INVENTORY)");
}
fn render(value: &serde_json::Value, args: &Args) -> anyhow::Result<String> {
Ok(if args.yaml {
to_yaml(value)?
} else if args.toml {
to_toml(value)?
} else {
to_json(value)
})
}