use std::fmt;
use vld::schema::VldParse;
#[derive(Debug, Clone)]
pub struct VldClapError {
pub source: ErrorSource,
pub message: String,
}
#[derive(Debug, Clone)]
pub enum ErrorSource {
Validation(vld::error::VldError),
Serialization(String),
}
impl VldClapError {
pub fn exit(&self) -> ! {
eprintln!("error: {}", self.message);
std::process::exit(2);
}
pub fn format_issues(&self) -> String {
match &self.source {
ErrorSource::Validation(_) => self
.message
.lines()
.skip(1)
.map(|l| format!(" {}", l.trim_start()))
.collect::<Vec<_>>()
.join("\n"),
ErrorSource::Serialization(msg) => format!(" {}", msg),
}
}
}
impl fmt::Display for VldClapError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.message)
}
}
impl std::error::Error for VldClapError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.source {
ErrorSource::Validation(e) => Some(e),
ErrorSource::Serialization(_) => None,
}
}
}
fn issue_line(i: &vld::error::ValidationIssue, cmd: Option<&clap::Command>) -> String {
use vld::error::PathSegment;
let arg = cmd.and_then(|cmd| {
i.path.iter().enumerate().find_map(|(n, seg)| match seg {
PathSegment::Field(id) => find_arg(cmd, id).map(|a| (n, a)),
_ => None,
})
});
let field = match arg {
Some((n, arg)) => {
let rest = vld::error::format_path(&i.path[n + 1..]);
let name = if let Some(long) = arg.get_long() {
format!("--{long}")
} else if let Some(short) = arg.get_short() {
format!("-{short}")
} else {
let value = arg
.get_value_names()
.and_then(|v| v.first())
.map(|v| v.to_string())
.unwrap_or_else(|| arg.get_id().as_str().to_uppercase());
format!("<{value}>")
};
let sep = if rest.is_empty() || rest.starts_with('[') {
""
} else {
"."
};
format!("{name}{sep}{rest}")
}
None => {
let field = vld::error::format_path(&i.path).replace('_', "-");
if field.is_empty() {
return i.message.clone();
}
format!("--{field}")
}
};
format!("{}: {}", field, i.message)
}
fn find_arg<'a>(cmd: &'a clap::Command, id: &str) -> Option<&'a clap::Arg> {
cmd.get_arguments()
.find(|a| a.get_id() == id)
.or_else(|| cmd.get_subcommands().find_map(|s| find_arg(s, id)))
}
fn make_error(e: vld::error::VldError) -> VldClapError {
make_error_for(e, None)
}
fn make_error_for(e: vld::error::VldError, cmd: Option<&clap::Command>) -> VldClapError {
let summary = e
.issues
.iter()
.map(|i| issue_line(i, cmd))
.collect::<Vec<_>>()
.join("\n ");
VldClapError {
message: format!("Invalid arguments:\n {}", summary),
source: ErrorSource::Validation(e),
}
}
pub fn validate<T>(args: &T) -> Result<(), VldClapError>
where
T: VldParse + serde::Serialize,
{
let json = serde_json::to_value(args).map_err(|e| VldClapError {
source: ErrorSource::Serialization(e.to_string()),
message: format!("Failed to serialize arguments: {}", e),
})?;
T::vld_parse_value(&json).map(|_| ()).map_err(make_error)
}
pub fn validate_cli<T>(args: &T) -> Result<(), VldClapError>
where
T: VldParse + serde::Serialize + clap::CommandFactory,
{
match validate(args) {
Err(VldClapError {
source: ErrorSource::Validation(e),
..
}) => Err(make_error_for(e, Some(&T::command()))),
other => other,
}
}
pub fn validate_or_exit<T>(args: &T)
where
T: VldParse + serde::Serialize + clap::CommandFactory,
{
if let Err(e) = validate_cli(args) {
e.exit();
}
}
pub fn validate_json<S>(json: &serde_json::Value) -> Result<S, VldClapError>
where
S: VldParse,
{
S::vld_parse_value(json).map_err(make_error)
}
pub fn validate_with_schema<S, T>(args: &T) -> Result<S, VldClapError>
where
S: VldParse,
T: serde::Serialize,
{
let json = serde_json::to_value(args).map_err(|e| VldClapError {
source: ErrorSource::Serialization(e.to_string()),
message: format!("Failed to serialize arguments: {}", e),
})?;
S::vld_parse_value(&json).map_err(make_error)
}
pub mod prelude {
pub use super::{
VldClapError, validate, validate_cli, validate_json, validate_or_exit, validate_with_schema,
};
pub use vld::prelude::*;
}