getargs_derive/error.rs
1/// An option as it was written on the command line, without its leading dashes.
2#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
3pub enum Opt<'a> {
4 /// A short option, like `-z` (stored as `'z'`).
5 Short(char),
6 /// A long option, like `--bogus` (stored as `"bogus"`).
7 Long(&'a str),
8}
9
10impl core::fmt::Display for Opt<'_> {
11 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
12 match self {
13 Opt::Short(short) => write!(f, "-{short}"),
14 Opt::Long(long) => write!(f, "--{long}"),
15 }
16 }
17}
18
19/// Errors that can occur when parsing CLI arguments with [`GetArgs`](crate::GetArgs).
20///
21/// The lifetime `'a` is the lifetime of the parsed arguments: variants describing what the
22/// user typed borrow it from the command line instead of copying it, so no allocation is needed.
23///
24/// Names of the struct's own arguments (`&'static str`) are written as in the generated help:
25/// `<INPUT>` for a positional argument, `--output <OUTPUT>` for an option taking a value
26/// (`-o <OUTPUT>` when it has no long name).
27///
28/// The enum is `#[non_exhaustive]`: new variants can be added in a minor release, so a `match` on
29/// it needs a wildcard arm.
30#[must_use]
31#[non_exhaustive]
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum Error<'a> {
34 /// A required positional argument or named option was not provided on the command line.
35 ///
36 /// The string is the argument name, e.g. `"<INPUT>"` or `"--output <OUTPUT>"`.
37 MissingArgument(&'static str),
38
39 /// An option that the struct does not define was given, e.g. `--bogus` or `-z`.
40 UnknownOption {
41 /// The unknown option, as written by the user.
42 option: Opt<'a>,
43 /// The closest long option name (without `--`) when an unknown long option looks like a
44 /// typo of a known one, e.g. `Some("verbose")` for `--verbos`.
45 suggestion: Option<&'static str>,
46 },
47
48 /// A positional argument was given but the struct expects no more of them.
49 ///
50 /// The string is the extra argument, as written by the user.
51 UnexpectedArgument(&'a str),
52
53 /// A value was attached to an option that does not take one, e.g. `--verbose=yes` for a flag.
54 ///
55 /// The option is the one written by the user.
56 UnexpectedValue(Opt<'a>),
57
58 /// An option taking a value was given without one, e.g. `--output` at the end of the
59 /// command line.
60 ///
61 /// The string is the option name, e.g. `"--output <OUTPUT>"`.
62 MissingOptionValue(&'static str),
63
64 /// Two arguments that cannot be used together were both given, because of `conflicts_with`
65 /// or because they belong to the same group.
66 ArgumentConflict {
67 /// The argument declaring the conflict (or the first member of the group), e.g.
68 /// `"--quiet"`.
69 name: &'static str,
70 /// The other argument, e.g. `"--verbose"`.
71 other: &'static str,
72 },
73
74 /// An argument was given without another argument it `requires`.
75 MissingRequiredArgument {
76 /// The missing argument, e.g. `"--output <OUTPUT>"`.
77 name: &'static str,
78 /// The given argument that requires it, e.g. `"--compress"`.
79 required_by: &'static str,
80 },
81
82 /// None of a set of arguments was given although one of them is required, because of
83 /// `required_unless_present` or a `required` group.
84 ///
85 /// The slice lists the arguments, e.g. `["--config <CONFIG>", "--stdin"]`.
86 MissingOneOf(&'static [&'static str]),
87
88 /// A required subcommand was not given.
89 ///
90 /// The slice lists the visible subcommands, e.g. `["add", "remove"]`. It is only returned for
91 /// a `#[command(subcommand)]` field that is not an `Option`.
92 MissingSubcommand(&'static [&'static str]),
93
94 /// A positional argument was given where a subcommand was expected, and it is not the name
95 /// or an alias of any subcommand.
96 UnknownSubcommand {
97 /// The unknown subcommand, as written by the user.
98 name: &'a str,
99 /// The closest visible subcommand name or alias when the unknown one looks like a typo of
100 /// it, e.g. `Some("remove")` for `remov`.
101 suggestion: Option<&'static str>,
102 },
103
104 /// The underlying `getargs` parser reported an error that this crate does not recognise.
105 ///
106 /// `getargs` may add error kinds in a compatible release; they are reported as this variant
107 /// instead of panicking. It is never returned with the `getargs` 0.5 releases known to this
108 /// crate.
109 InvalidArguments,
110
111 /// A value could not be parsed into the target field type, e.g. `abc` for a `u32` field.
112 ///
113 /// This is also returned when a `default_value` string does not parse, and when a
114 /// `value_parser` function rejects a value with an error that is not a `&str`.
115 InvalidValue {
116 /// The argument name, e.g. `"--port <PORT>"` or `"<COUNT>"`.
117 name: &'static str,
118 /// The value that failed to parse.
119 value: &'a str,
120 },
121
122 /// A `value_parser` function rejected a value with a `&str` error, kept as the reason.
123 ///
124 /// This is also returned when the function rejects a `default_value` string or the value of
125 /// an environment variable.
126 InvalidValueReason {
127 /// The argument name, e.g. `"--port <PORT>"`.
128 name: &'static str,
129 /// The value that was rejected.
130 value: &'a str,
131 /// The error returned by the function, e.g. `"must be at least 1024"`.
132 reason: &'a str,
133 },
134
135 /// A value is not one of the argument's `possible_values`, e.g. `turbo` for
136 /// `possible_values = ["fast", "slow"]`.
137 ///
138 /// This is also returned when a `default_value` string is not one of them.
139 InvalidPossibleValue {
140 /// The argument name, e.g. `"--mode <MODE>"`.
141 name: &'static str,
142 /// The value that was given.
143 value: &'a str,
144 /// The accepted values, in declaration order, e.g. `["fast", "slow"]`.
145 possible_values: &'static [&'static str],
146 },
147
148 /// A value parsed into the field type but is outside the argument's `value_parser` range,
149 /// e.g. `0` for `value_parser = 1..=64`.
150 ///
151 /// This is also returned when a `default_value` string is outside the range.
152 ValueOutOfRange {
153 /// The argument name, e.g. `"--jobs <JOBS>"`.
154 name: &'static str,
155 /// The value that was given.
156 value: &'a str,
157 /// The range as written in the attribute, e.g. `"1..=64"`.
158 range: &'static str,
159 },
160
161 /// More values were given to a repeated argument than its collection can hold, or than its
162 /// `num_args` range accepts, e.g. a third `-I` for a `Values<&str, 2>` field.
163 ///
164 /// This is also returned when an environment variable or a default splits into too many
165 /// values.
166 TooManyValues {
167 /// The argument name, e.g. `"--include <INCLUDE>"` or `"<FILES>..."`.
168 name: &'static str,
169 /// The first value that did not fit.
170 value: &'a str,
171 /// The maximum number of values.
172 max: usize,
173 },
174
175 /// A positional argument collecting several values received fewer than the minimum of its
176 /// `num_args` range, but at least one. [`Error::MissingArgument`] is returned when it received
177 /// none.
178 TooFewValues {
179 /// The argument name, e.g. `"<FILES>..."`.
180 name: &'static str,
181 /// The minimum number of values.
182 min: usize,
183 /// The number of values given.
184 actual: usize,
185 },
186
187 /// An argument that is not valid UTF-8 was given where text is required, when parsing raw
188 /// bytes with `from_bytes`, `parse_bytes` or `from_args_os`.
189 ///
190 /// It is returned for a value of a `&str` field or of a field parsed from a string, and for an
191 /// argument that matches no field, such as an option name, a subcommand name or an extra
192 /// positional argument, since those are reported as text by the other variants.
193 InvalidUtf8 {
194 /// The argument name, e.g. `"--name <NAME>"`, or `None` for an argument that matches no
195 /// field.
196 name: Option<&'static str>,
197 /// The raw bytes of the argument, displayed with [`Lossy`](crate::Lossy).
198 value: &'a [u8],
199 },
200
201 /// Help was requested with `-h` or `--help`.
202 ///
203 /// This is not a parse failure: the string is the generated help text, the struct's `HELP`
204 /// constant for `-h` and its `LONG_HELP` constant for `--help`. After a subcommand, it is the
205 /// help of that subcommand instead. Applications should print it to standard output and exit
206 /// successfully.
207 /// It is never returned when help is disabled with `#[command(disable_help_flag)]`.
208 Help(&'static str),
209
210 /// The version was requested with `-V` or `--version`.
211 ///
212 /// This is not a parse failure: the string is the version line, the command name followed by
213 /// the version (the struct's `VERSION_TEXT` constant). Applications should print it to standard
214 /// output and exit successfully. It is only returned when `#[command(version)]` is set.
215 Version(&'static str),
216}
217
218impl<'a> Error<'a> {
219 /// Returns `true` if this is [`Error::Help`], i.e. the user asked for help rather than
220 /// passing invalid arguments.
221 #[must_use]
222 pub fn is_help(&self) -> bool {
223 matches!(self, Error::Help(_))
224 }
225
226 /// Returns `true` if this is [`Error::Version`], i.e. the user asked for the version rather
227 /// than passing invalid arguments.
228 #[must_use]
229 pub fn is_version(&self) -> bool {
230 matches!(self, Error::Version(_))
231 }
232
233 /// Pairs the error with the usage of the command, so that its `Display` ends with the usage
234 /// line and a hint to try `--help`, as Clap errors do. See [`WithUsage`].
235 ///
236 /// The usage of a struct deriving `GetArgs` is its `USAGE` constant. For an error raised
237 /// by a subcommand it is the usage of the struct holding the subcommand, not of the
238 /// subcommand.
239 ///
240 /// ```
241 /// # use getargs_derive::GetArgs;
242 /// #[derive(Debug, GetArgs)]
243 /// #[command(name = "copy")]
244 /// struct Cli<'a> {
245 /// input: &'a str,
246 /// }
247 ///
248 /// let error = Cli::from_args(["a", "b"].into_iter()).unwrap_err();
249 /// assert_eq!(
250 /// error.with_usage(Cli::USAGE).to_string(),
251 /// "unexpected argument 'b' found\n\nUsage: copy [OPTIONS] <INPUT>\n\nFor more information, try '--help'."
252 /// );
253 /// ```
254 pub const fn with_usage(self, usage: Usage) -> WithUsage<'a> {
255 WithUsage { error: self, usage }
256 }
257}
258
259impl core::fmt::Display for Error<'_> {
260 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
261 match self {
262 Error::MissingArgument(name) => {
263 write!(
264 f,
265 "the following required argument was not provided: {name}"
266 )
267 }
268 Error::UnknownOption { option, suggestion } => {
269 write!(f, "unexpected argument '{option}' found")?;
270 match suggestion {
271 Some(suggestion) => {
272 write!(f, "\n\n tip: a similar argument exists: '--{suggestion}'")
273 }
274 None => Ok(()),
275 }
276 }
277 Error::UnexpectedArgument(argument) => {
278 write!(f, "unexpected argument '{argument}' found")
279 }
280 Error::UnexpectedValue(option) => {
281 write!(
282 f,
283 "unexpected value for '{option}': it does not take a value"
284 )
285 }
286 Error::ArgumentConflict { name, other } => {
287 write!(f, "the argument '{name}' cannot be used with '{other}'")
288 }
289 Error::MissingRequiredArgument { name, required_by } => {
290 write!(
291 f,
292 "the following required argument was not provided: {name} (required by '{required_by}')"
293 )
294 }
295 Error::MissingOneOf(names) => {
296 f.write_str("the following required arguments were not provided: <")?;
297 for (index, name) in names.iter().enumerate() {
298 if index > 0 {
299 f.write_str("|")?;
300 }
301 f.write_str(name)?;
302 }
303 f.write_str(">")
304 }
305 Error::MissingSubcommand(names) => {
306 f.write_str(
307 "a subcommand is required but one was not provided\n\n [subcommands: ",
308 )?;
309 for (index, name) in names.iter().enumerate() {
310 if index > 0 {
311 f.write_str(", ")?;
312 }
313 f.write_str(name)?;
314 }
315 f.write_str("]")
316 }
317 Error::UnknownSubcommand { name, suggestion } => {
318 write!(f, "unrecognized subcommand '{name}'")?;
319 match suggestion {
320 Some(suggestion) => {
321 write!(f, "\n\n tip: a similar subcommand exists: '{suggestion}'")
322 }
323 None => Ok(()),
324 }
325 }
326 Error::InvalidArguments => f.write_str("the arguments could not be parsed"),
327 Error::MissingOptionValue(name) => {
328 write!(f, "a value is required for '{name}' but none was supplied")
329 }
330 Error::InvalidValue { name, value } => {
331 write!(f, "invalid value '{value}' for '{name}'")
332 }
333 Error::InvalidValueReason {
334 name,
335 value,
336 reason,
337 } => {
338 write!(f, "invalid value '{value}' for '{name}': {reason}")
339 }
340 Error::InvalidPossibleValue {
341 name,
342 value,
343 possible_values,
344 } => {
345 write!(
346 f,
347 "invalid value '{value}' for '{name}'\n [possible values: "
348 )?;
349 for (index, possible) in possible_values.iter().enumerate() {
350 if index > 0 {
351 f.write_str(", ")?;
352 }
353 if possible.is_empty() || possible.contains(char::is_whitespace) {
354 write!(f, "{possible:?}")?;
355 } else {
356 f.write_str(possible)?;
357 }
358 }
359 f.write_str("]")
360 }
361 Error::ValueOutOfRange { name, value, range } => {
362 write!(
363 f,
364 "invalid value '{value}' for '{name}': {value} is not in {range}"
365 )
366 }
367 Error::TooManyValues { name, value, .. } => {
368 write!(
369 f,
370 "unexpected value '{value}' for '{name}' found; no more were expected"
371 )
372 }
373 Error::TooFewValues { name, min, actual } => {
374 let verb = if *actual == 1 { "was" } else { "were" };
375 write!(
376 f,
377 "{min} values required by '{name}'; only {actual} {verb} provided"
378 )
379 }
380 Error::InvalidUtf8 {
381 name: Some(name),
382 value,
383 } => {
384 write!(
385 f,
386 "invalid UTF-8 in value '{}' for '{name}'",
387 crate::Lossy(value)
388 )
389 }
390 Error::InvalidUtf8 { name: None, value } => {
391 write!(f, "invalid UTF-8 in argument '{}'", crate::Lossy(value))
392 }
393 Error::Help(help) => f.write_str(help),
394 Error::Version(version) => f.write_str(version),
395 }
396 }
397}
398
399impl core::error::Error for Error<'_> {}
400
401/// The usage line of a command and whether it has a help flag, to remind the user of both after
402/// an argument error, as Clap does.
403///
404/// The `GetArgs` derive generates one as the `USAGE` constant of the struct, built at compile
405/// time without allocation. Its `Display` shows the usage line alone, e.g.
406/// `Usage: copy [OPTIONS] <INPUT>`. Pass it to [`Error::with_usage`] to show it after an error.
407#[derive(Debug, Clone, Copy, PartialEq, Eq)]
408#[non_exhaustive]
409pub struct Usage {
410 /// The usage line, starting with `Usage: ` and without a trailing newline.
411 pub line: &'static str,
412 /// Whether the command has a help flag, which the hint after the usage line refers to.
413 pub help_flag: bool,
414}
415
416impl Usage {
417 /// A usage with the line `line` and a help flag.
418 #[must_use]
419 pub const fn new(line: &'static str) -> Self {
420 Usage {
421 line,
422 help_flag: true,
423 }
424 }
425
426 /// Sets [`help_flag`](Self::help_flag).
427 #[must_use]
428 pub const fn help_flag(mut self, help_flag: bool) -> Self {
429 self.help_flag = help_flag;
430 self
431 }
432}
433
434impl core::fmt::Display for Usage {
435 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
436 f.write_str(self.line)
437 }
438}
439
440/// An [`Error`] followed by a usage line and a help hint, returned by [`Error::with_usage`].
441///
442/// Its `Display` writes the message of the error, a blank line, the usage line, another blank
443/// line and `For more information, try '--help'.` (left out when the command has no help flag),
444/// like the end of a Clap error:
445///
446/// ```text
447/// invalid value 'x' for '--mode <MODE>'
448/// [possible values: fast, slow]
449///
450/// Usage: run [OPTIONS]
451///
452/// For more information, try '--help'.
453/// ```
454///
455/// [`Error::Help`] and [`Error::Version`] are not failures and are written alone.
456#[must_use]
457#[derive(Debug, Clone, Copy, PartialEq, Eq)]
458pub struct WithUsage<'a> {
459 error: Error<'a>,
460 usage: Usage,
461}
462
463impl<'a> WithUsage<'a> {
464 /// The error being reported.
465 pub const fn error(&self) -> &Error<'a> {
466 &self.error
467 }
468
469 /// The usage shown after the error.
470 pub const fn usage(&self) -> &Usage {
471 &self.usage
472 }
473}
474
475impl core::fmt::Display for WithUsage<'_> {
476 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
477 write!(f, "{}", self.error)?;
478 if self.error.is_help() || self.error.is_version() {
479 return Ok(());
480 }
481 write!(f, "\n\n{}", self.usage)?;
482 if self.usage.help_flag {
483 f.write_str("\n\nFor more information, try '--help'.")?;
484 }
485 Ok(())
486 }
487}
488
489impl core::error::Error for WithUsage<'_> {}