vld_app/clap.rs
1//! # `vld_app::clap` — validate clap arguments with `vld`
2//!
3//! clap parses types, defaults and required arguments; `vld_app::clap` checks the
4//! values (formats, ranges, lengths) afterwards, using `#[derive(Validate)]`
5//! rules on the same clap struct. No separate schema.
6//!
7//! ```rust
8//! use clap::Parser;
9//! use vld::Validate;
10//!
11//! #[derive(Parser, Debug, serde::Serialize, Validate)]
12//! struct Cli {
13//! /// Admin email address
14//! #[arg(long)]
15//! #[vld(vld::string().email())]
16//! email: String,
17//!
18//! /// Server port
19//! #[arg(long, default_value_t = 8080)]
20//! #[vld(vld::number().int().min(1).max(65535))]
21//! port: i64,
22//!
23//! /// Output file
24//! #[arg(long = "out")]
25//! #[vld(vld::string().min(1))]
26//! output_file: String,
27//! }
28//!
29//! let cli = Cli::parse_from(["app", "--email", "nope", "--port", "0", "--out", "x"]);
30//! let err = vld_app::clap::validate_cli(&cli).unwrap_err();
31//! assert_eq!(
32//! err.message,
33//! "Invalid arguments:\n --email: Invalid email address\n --port: Number must be at least 1",
34//! );
35//! // In `main`: `vld_app::clap::validate_or_exit(&cli)` prints this and exits with code 2.
36//! ```
37//!
38//! # Flag names in errors
39//!
40//! [`validate_cli`] and [`validate_or_exit`] (for `clap::Parser` /
41//! `CommandFactory` types) name each argument the way clap does:
42//! `#[arg(long = "out")] output_file` is `--out`, a positional `input` is
43//! `<INPUT>`. [`validate`] works on any `Serialize` struct and guesses
44//! `--kebab-case` from the field name.
45//!
46//! Guide: <https://s00d.github.io/vld/integrations/config-cli/clap>
47
48use std::fmt;
49use vld::schema::VldParse;
50
51// ---------------------------------------------------------------------------
52// Error type
53// ---------------------------------------------------------------------------
54
55/// Error returned by `vld_app::clap` validation functions.
56#[derive(Debug, Clone)]
57pub struct VldClapError {
58 /// The underlying vld validation error (if any).
59 pub source: ErrorSource,
60 /// Human-readable summary of all issues for CLI display.
61 pub message: String,
62}
63
64/// Source of the error.
65#[derive(Debug, Clone)]
66pub enum ErrorSource {
67 /// Validation failed.
68 Validation(vld::error::VldError),
69 /// Serialization to JSON failed.
70 Serialization(String),
71}
72
73impl VldClapError {
74 /// Print the error to stderr and exit with code 2 (standard for usage errors).
75 pub fn exit(&self) -> ! {
76 eprintln!("error: {}", self.message);
77 std::process::exit(2);
78 }
79
80 /// Format each issue on its own line, prefixed with the flag name
81 /// (as in [`message`](Self::message)).
82 pub fn format_issues(&self) -> String {
83 match &self.source {
84 ErrorSource::Validation(_) => self
85 .message
86 .lines()
87 .skip(1)
88 .map(|l| format!(" {}", l.trim_start()))
89 .collect::<Vec<_>>()
90 .join("\n"),
91 ErrorSource::Serialization(msg) => format!(" {}", msg),
92 }
93 }
94}
95
96impl fmt::Display for VldClapError {
97 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98 write!(f, "{}", self.message)
99 }
100}
101
102impl std::error::Error for VldClapError {
103 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
104 match &self.source {
105 ErrorSource::Validation(e) => Some(e),
106 ErrorSource::Serialization(_) => None,
107 }
108 }
109}
110
111// ---------------------------------------------------------------------------
112// Core validation functions
113// ---------------------------------------------------------------------------
114
115/// `--flag-name: message`. With a clap `Command` the field's argument is
116/// looked up (`--out`, `-o`, `<INPUT>`); otherwise clap's default kebab-case
117/// flag name is assumed (`max_connections` -> `--max-connections`, nested
118/// `user.email` -> `--user.email`).
119fn issue_line(i: &vld::error::ValidationIssue, cmd: Option<&clap::Command>) -> String {
120 use vld::error::PathSegment;
121 // The outermost path field that names an argument of the command, a
122 // flattened group (already merged into the command) or a subcommand.
123 let arg = cmd.and_then(|cmd| {
124 i.path.iter().enumerate().find_map(|(n, seg)| match seg {
125 PathSegment::Field(id) => find_arg(cmd, id).map(|a| (n, a)),
126 _ => None,
127 })
128 });
129 let field = match arg {
130 Some((n, arg)) => {
131 let rest = vld::error::format_path(&i.path[n + 1..]);
132 let name = if let Some(long) = arg.get_long() {
133 format!("--{long}")
134 } else if let Some(short) = arg.get_short() {
135 format!("-{short}")
136 } else {
137 let value = arg
138 .get_value_names()
139 .and_then(|v| v.first())
140 .map(|v| v.to_string())
141 .unwrap_or_else(|| arg.get_id().as_str().to_uppercase());
142 format!("<{value}>")
143 };
144 // `<FILES>[0]`, `--tag[0]`, `--db.url`
145 let sep = if rest.is_empty() || rest.starts_with('[') {
146 ""
147 } else {
148 "."
149 };
150 format!("{name}{sep}{rest}")
151 }
152 None => {
153 let field = vld::error::format_path(&i.path).replace('_', "-");
154 if field.is_empty() {
155 return i.message.clone();
156 }
157 format!("--{field}")
158 }
159 };
160 format!("{}: {}", field, i.message)
161}
162
163/// Argument `id` of `cmd` or of any (nested) subcommand.
164fn find_arg<'a>(cmd: &'a clap::Command, id: &str) -> Option<&'a clap::Arg> {
165 cmd.get_arguments()
166 .find(|a| a.get_id() == id)
167 .or_else(|| cmd.get_subcommands().find_map(|s| find_arg(s, id)))
168}
169
170fn make_error(e: vld::error::VldError) -> VldClapError {
171 make_error_for(e, None)
172}
173
174fn make_error_for(e: vld::error::VldError, cmd: Option<&clap::Command>) -> VldClapError {
175 let summary = e
176 .issues
177 .iter()
178 .map(|i| issue_line(i, cmd))
179 .collect::<Vec<_>>()
180 .join("\n ");
181 VldClapError {
182 message: format!("Invalid arguments:\n {}", summary),
183 source: ErrorSource::Validation(e),
184 }
185}
186
187/// Validate a parsed CLI struct that implements `#[derive(Validate)]` + `Serialize`.
188///
189/// The struct is serialized to JSON, then validated via the vld rules
190/// defined by `#[vld(...)]` attributes on its fields.
191///
192/// # Example
193///
194/// ```rust
195/// use vld::Validate;
196///
197/// #[derive(Debug, serde::Serialize, Validate)]
198/// struct Args {
199/// #[vld(vld::number().int().min(1).max(65535))]
200/// port: i64,
201/// #[vld(vld::string().min(1))]
202/// host: String,
203/// }
204///
205/// let args = Args { port: 8080, host: "localhost".into() };
206/// assert!(vld_app::clap::validate(&args).is_ok());
207///
208/// let bad = Args { port: 0, host: "".into() };
209/// assert!(vld_app::clap::validate(&bad).is_err());
210/// ```
211pub fn validate<T>(args: &T) -> Result<(), VldClapError>
212where
213 T: VldParse + serde::Serialize,
214{
215 let json = serde_json::to_value(args).map_err(|e| VldClapError {
216 source: ErrorSource::Serialization(e.to_string()),
217 message: format!("Failed to serialize arguments: {}", e),
218 })?;
219 T::vld_parse_value(&json).map(|_| ()).map_err(make_error)
220}
221
222/// Like [`validate`], for a clap `Parser`: errors name each argument as
223/// clap does (`#[arg(long = "out")]` → `--out`, positional → `<INPUT>`).
224pub fn validate_cli<T>(args: &T) -> Result<(), VldClapError>
225where
226 T: VldParse + serde::Serialize + clap::CommandFactory,
227{
228 match validate(args) {
229 Err(VldClapError {
230 source: ErrorSource::Validation(e),
231 ..
232 }) => Err(make_error_for(e, Some(&T::command()))),
233 other => other,
234 }
235}
236
237/// Validate and exit on failure — convenience wrapper.
238///
239/// Calls [`validate_cli`] and, on error, prints the error to stderr
240/// and exits with code 2.
241///
242/// ```rust,ignore
243/// let cli = Cli::parse();
244/// vld_app::clap::validate_or_exit(&cli);
245/// println!("All good: {:?}", cli);
246/// ```
247pub fn validate_or_exit<T>(args: &T)
248where
249 T: VldParse + serde::Serialize + clap::CommandFactory,
250{
251 if let Err(e) = validate_cli(args) {
252 e.exit();
253 }
254}
255
256/// Validate a JSON value against any `VldParse` schema `S`.
257///
258/// Useful when the CLI args are already a JSON object.
259pub fn validate_json<S>(json: &serde_json::Value) -> Result<S, VldClapError>
260where
261 S: VldParse,
262{
263 S::vld_parse_value(json).map_err(make_error)
264}
265
266/// Validate a `Serialize`-able value against any `VldParse` schema `S`.
267///
268/// Use this when you have a separate schema and a data struct (the old
269/// pattern). Prefer [`validate`] with `#[derive(Validate)]` for the
270/// idiomatic approach.
271pub fn validate_with_schema<S, T>(args: &T) -> Result<S, VldClapError>
272where
273 S: VldParse,
274 T: serde::Serialize,
275{
276 let json = serde_json::to_value(args).map_err(|e| VldClapError {
277 source: ErrorSource::Serialization(e.to_string()),
278 message: format!("Failed to serialize arguments: {}", e),
279 })?;
280 S::vld_parse_value(&json).map_err(make_error)
281}
282
283// ---------------------------------------------------------------------------
284// Prelude
285// ---------------------------------------------------------------------------
286
287/// Prelude — import everything you need.
288pub mod prelude {
289 pub use super::{
290 VldClapError, validate, validate_cli, validate_json, validate_or_exit, validate_with_schema,
291 };
292 pub use vld::prelude::*;
293}