Files
wara/src/config/cli.rs

302 lines
7.8 KiB
Rust

/*
* Copyright (c) 2026 MCorange.
* All rights reserved.
*
* Unauthorized copying, modification, distribution, or use of this
* software, in whole or in part, is prohibited without prior written
* permission.
*/
use std::net::IpAddr;
use clap::ArgGroup;
#[derive(Debug, Clone, clap::Parser, Default)]
#[command(
author = env!("CARGO_PKG_AUTHORS"),
version,
after_help = concat!(
"Made by: ", env!("CARGO_PKG_AUTHORS"), "\n",
"All Rights Reserved"
)
)]
pub struct CliArgs {
/// Configuration file path
#[arg(long = "config", short = 'C', default_value = "./config.toml")]
pub config_file: camino::Utf8PathBuf,
/// Output more information in logs
#[arg(long = "verbose", short = 'v', conflicts_with = "quiet")]
pub verbose: bool,
/// Output more information in logs
#[arg(long = "quiet", short = 'q', conflicts_with = "verbose")]
pub quiet: bool,
#[command(subcommand)]
pub command: CliCommand,
}
#[derive(Debug, Clone, clap::Subcommand, Default)]
pub enum CliCommand {
/// Run command once
#[command(
group(
ArgGroup::new("devs")
.args(["all", "devices"])
.required(true)
)
)]
Run {
/// Run on ALL devices
#[arg(long, short = 'a')]
all: bool,
/// Run on all specified devices
#[arg(long, short = 'd')]
devices: Vec<String>,
/// Command to run
#[arg(long, short = 'c')]
command: String,
/// Output format
#[arg(long, short = 'f')]
format: OutputFormat,
/// Filter command results (key=value)
#[arg(long, short = 'F', value_parser = parse_filter)]
filter: Vec<Filter>,
/// Add a command attribute (key=value or flag; repeatable)
#[arg(long, short = 'A', value_parser = parse_attribute)]
attributes: Vec<(String, Option<String>)>,
},
/// Run command continuosly
#[command(
group(
ArgGroup::new("devs")
.args(["all", "devices"])
.required(true)
)
)]
Monitor {
/// Run on ALL devices
#[arg(long, short = 'a')]
all: bool,
/// Run on all specified devices
#[arg(long, short = 'd')]
devices: Vec<String>,
/// Command to run
#[arg(long, short = 'c')]
command: String,
/// Output format
#[arg(long, short = 'f')]
format: OutputFormat,
/// Interval to run the commands at
#[arg(long, short = 'i')]
interval: f32,
},
/// Manage devices
Device {
#[command(subcommand)]
command: CliDeviceCommand,
},
BesWifi {
#[arg(long, short = 'i', value_parser = humantime::parse_duration, default_value="5m")]
interval: std::time::Duration,
#[arg(long, short = 'C', value_parser = humantime::parse_duration, default_value="1w")]
cleanup_interval: std::time::Duration,
},
#[default]
#[clap(skip)]
None,
}
#[derive(Debug, Clone, clap::Subcommand, Default)]
pub enum CliDeviceCommand {
/// List devices
List,
Add {
/// Device name
#[arg(short = 'n', long)]
name: String,
/// Device address, ipv4 or ipv6
#[arg(short = 'H', long)]
host: IpAddr,
/// Device Port (skip for default)
#[arg(short = 'p', long)]
port: Option<u16>,
/// Username (skip for default)
#[arg(short = 'U', long)]
username: Option<String>,
/// Password (skip for default)
#[arg(short = 'P', long)]
password: Option<String>,
},
Remove {
/// Name of the device
#[arg(short, long)]
name: String,
},
#[default]
#[clap(skip)]
None,
}
#[derive(Clone, Debug, Default, clap::ValueEnum)]
pub enum OutputFormat {
#[default]
Csv,
Table,
Json,
}
#[derive(Debug, Clone, Copy)]
pub enum FilterOp {
Eq,
Gt,
Lt,
Neq,
Ge,
Le,
}
#[derive(Debug, Clone)]
pub struct Filter {
pub key: String,
pub op: FilterOp,
pub value: String,
}
#[derive(Debug, Clone)]
pub struct MtCommand {
pub cmd: String,
pub attr: Vec<(String, Option<String>)>,
pub filter: Vec<Filter>
}
pub struct MtCommandBuilder(MtCommand);
impl MtCommand {
pub fn new(cmd: &str, attr: Vec<(String, Option<String>)>, filter: Vec<Filter>) -> Self {
Self {
cmd: cmd.to_string(),
attr, filter
}
}
pub fn builder(cmd: &str) -> MtCommandBuilder {
MtCommandBuilder(Self {
cmd: cmd.to_string(),
attr: Default::default(),
filter: Default::default()
})
}
pub fn new_basic(cmd: &str) -> Self {
Self {
cmd: cmd.to_string(),
attr: Default::default(),
filter: Default::default()
}
}
}
impl MtCommandBuilder {
pub fn attribute_raw(mut self, key: String, value: Option<String>) -> Self {
self.0.attr.push((key, value));
self
}
pub fn filter_raw(mut self, key: String, op: FilterOp, value: String) -> Self {
self.0.filter.push(Filter { key, op, value });
self
}
pub fn attribute(self, s: &str) -> anyhow::Result<Self> {
let (key, value) = parse_attribute(&s).map_err(|e| anyhow::anyhow!(e))?;
Ok(self.attribute_raw(key, value))
}
pub fn filter(self, s: &str) -> anyhow::Result<Self> {
let Filter{key, op, value} = parse_filter(&s).map_err(|e| anyhow::anyhow!(e))?;
Ok(self.filter_raw(key, op, value))
}
pub fn build(self) -> MtCommand {
self.0
}
}
impl std::fmt::Display for MtCommand {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.cmd)?;
let mut words = Vec::new();
for filter in &self.filter {
let (operator, negate) = match filter.op {
FilterOp::Eq => ('=', false),
FilterOp::Neq => ('=', true),
FilterOp::Gt => ('>', false),
FilterOp::Lt => ('<', false),
FilterOp::Ge => ('<', true),
FilterOp::Le => ('>', true),
};
let prefix = match operator {
'>' => ">",
'<' => "<",
_ => "",
};
words.push(format!("?{prefix}{}={}", filter.key, filter.value));
if negate {
words.push("?#!".to_string());
}
}
for (key, value) in &self.attr {
words.push(match value {
Some(value) => format!("&={key}={value}"),
None => format!("&={key}"),
});
}
if !words.is_empty() {
write!(f, "{}", words.join(""))?;
}
Ok(())
}
}
fn parse_filter(s: &str) -> Result<Filter, String> {
let (key, op, value) = [">=", "<=", "!=", "=", ">", "<"]
.into_iter()
.find_map(|op| {
s.split_once(op)
.map(|(key, value)| (key, op, value))
})
.ok_or_else(|| format!("invalid filter: {s}"))?;
let op = match op {
"=" => FilterOp::Eq,
"!=" => FilterOp::Neq,
">" => FilterOp::Gt,
"<" => FilterOp::Lt,
">=" => FilterOp::Ge,
"<=" => FilterOp::Le,
_ => unreachable!(),
};
Ok(Filter {
key: key.trim().to_string(),
op,
value: value.trim().to_string(),
})
}
fn parse_attribute(s: &str) -> Result<(String, Option<String>), String> {
let s = s.trim();
if let Some((key, value)) = s.split_once('=') {
Ok((key.trim().to_string(), Some(value.trim().to_string())))
} else if !s.is_empty() {
Ok((s.to_string(), None))
} else {
Err("empty attribute".to_string())
}
}